package com.yycx.module.bus.provider.service.hy.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.NumberChineseFormatter;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yycx.common.utils.*;
import com.yycx.module.bus.client.entity.hy.BusPaymentOrder;
import com.yycx.module.bus.client.entity.hy.*;
import com.yycx.module.bus.provider.handler.haiying.BusinessUtils;
import com.yycx.module.bus.provider.service.hy.BusPaymentOrderService;
import com.yycx.bpm.provider.common.CommentTypeEnum;
import com.yycx.bpm.provider.service.ProcessInstanceService;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.base.service.impl.BaseServiceImpl;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.common.mybatis.query.CriteriaDelete;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.mybatis.query.CriteriaSave;
import com.yycx.common.mybatis.query.CriteriaUpdate;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.security.OpenUser;
import com.yycx.groovy.provider.script.MyGroovyScriptEngine;
import com.yycx.module.admin.client.entity.BaseUser;
import com.yycx.module.admin.provider.service.BaseRoleService;
import com.yycx.module.admin.provider.service.BaseUserService;
import com.yycx.module.bus.client.entity.*;
import com.yycx.module.bus.client.enums.*;
import com.yycx.module.bus.client.vo.HyBankItem;
import com.yycx.module.bus.client.vo.HyOrderItemVo;
import com.yycx.module.bus.provider.handler.haiying.HyOrderUtils;
import com.yycx.module.bus.provider.mapper.hy.HyOrderMapper;
import com.yycx.module.bus.provider.service.*;
import com.yycx.module.bus.provider.service.hy.*;
import com.yycx.module.file.provider.service.SysFileService;
import com.yycx.module.system.client.entity.SysBank;
import com.yycx.module.system.client.entity.SysCompany;
import com.yycx.module.system.client.entity.SysPrintDesigner;
import com.yycx.module.system.provider.service.SysAreaService;
import com.yycx.module.system.provider.service.SysBankService;
import com.yycx.module.system.provider.service.SysCompanyService;
import com.yycx.module.system.provider.service.SysPrintDesignerService;
import com.yycx.module.user.client.entity.AppPosition;
import com.yycx.module.user.provider.service.AppPositionService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.TaskService;
import org.flowable.engine.task.Comment;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.swing.text.html.parser.Entity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 海鹰销售单接口实现类
 *
 * @author flyme
 * @date 2020-08-17
 */
@Service
@Slf4j
public class HyOrderServiceImpl extends BaseServiceImpl<HyOrderMapper, HyOrder> implements HyOrderService {

    @Autowired
    private HyRemoteOrderService hyRemoteOrderService;

    @Autowired
    private HyOrderDetailService hyOrderDetailService;

    @Resource
    private SysFileService fileService;

    @Resource
    private BusPaymentService paymentService;


    @Resource
    private BusSalemanService saleManService;


    @Resource
    private SysCompanyService companyService;

    @Resource
    private HyOrderUtils hyOrderUtils;

    @Resource
    private BusinessUtils businessUtils;


    @Resource
    private AppPositionService positionService;

    @Resource
    private BusDeptService deptService;

    @Resource
    private BusCustomService customService;

    @Resource
    private BusCustomBalanceService customBalanceService;

    @Resource
    private SysBankService bankService;


    @Resource
    private BaseUserService userService;


    @Autowired
    private TaskService taskService;

    @Autowired
    private BaseRoleService roleService;


    @Autowired
    private BusDeptHyService deptHyService;

    @Autowired
    private BusPaymentOrderService paymentOrderService;
    @Resource
    private BusBankStatementService bankStatementService;

    @Autowired
    private SysPrintDesignerService sysPrintDesignerService;

    @Autowired
    private BusHyorderReturnService hyorderReturnService;
    @Resource
    private BaseUserService baseUserService;
    @Resource
    private BusDrugsService drugsService;

    @Override
    public ResultBody beforePageList(CriteriaQuery<HyOrder> cq, HyOrder hyOrder, EntityMap requestMap) {
        String customName = cq.getParams("customName");
        cq.select(HyOrder.class, "*");
        cq.addSelect(BusDept.class, "deptName", "deptType");
        cq.addSelect(BusCustom.class, "customName");
        if (FlymeUtils.isNotEmpty(customName)) {
            String pinyin = PinyinUtil.getFirstLetter(customName, "").toUpperCase();
            cq.and(e -> e.like("custom.customName", customName).or().likeRight("custom.customNamePinYin", pinyin));
        }
        cq.eq(HyOrder.class, "ho.saleManName");
        cq.createJoin(BusDept.class);
        cq.createJoin(BusCustom.class);
        cq.orderByDesc("ho.createTime");
        return super.beforePageList(cq, hyOrder, requestMap);
    }

    @Override
    public List<EntityMap> afterPageList(CriteriaQuery<HyOrder> cq, List<EntityMap> data, ResultBody resultBody) {
        for (EntityMap entityMap : data) {
            String customCode = entityMap.get("customCode");
            if (FlymeUtils.isNotEmpty(customCode)) {
            }
        }
        return super.afterPageList(cq, data, resultBody);
    }

    /**
     * 订单检测
     *
     * @param isAdd
     * @param hyOrder
     */
    public BusSaleman checkOrder(HyOrder hyOrder, Boolean isAdd, Integer historyOrder) {
        Long saleManId = hyOrder.getSaleManId();
        ApiAssert.isNotEmpty("业务员ID不能为空", saleManId);
        BusSaleman saleMan = saleManService.getById(saleManId);
        ApiAssert.isNotEmpty("业务员不能为空", saleMan);
        Long positionId = saleMan.getPositionId();
        ApiAssert.isNotEmpty("业务员职务未设置", positionId);
        String customCode = hyOrder.getCustomCode();
        ApiAssert.isNotEmpty("发货区域不能为空", hyOrder.getSendArea());
        String orderId = hyOrder.getOrderId();
        String deptType = hyOrder.getDeptType();
        String businessArea = saleMan.getAreaShortName();
        if (deptType.equals(DeptTypeEnum.ZS.getCode())) {
            businessArea = saleMan.getSaleManBusinessNo();
        }
        ApiAssert.isNotEmpty("业务编码未设置", businessArea);
        hyOrder.setBusinessArea(businessArea);
        //历史订单编辑直接返回
        if (historyOrder.equals(1)) {
            return saleMan;
        }
        //订单销售金额
        BigDecimal totalSaleAmount = FlymeUtils.getBigDecimal(hyOrder.getTotalSaleAmount(), "0");
        //票折金额
        BigDecimal totalDiscountAmount = FlymeUtils.getBigDecimal(hyOrder.getTotalDiscountAmount(), "0");
        //发货方式
        Integer sendType = hyOrder.getSendType();
        //全额资信检测资信额度
        if (SendTypeEnum.QZ.getCode().equals(sendType)) {
            //资信额度
            BigDecimal reputationAmount = FlymeUtils.getBigDecimal(saleMan.getReputationAmount(), "0");
            //已用资信额度
            BigDecimal alreadyAmount = hyOrderDetailService.totalReputationAmount(saleMan.getSaleManId()).add(totalSaleAmount);
            if (FlymeUtils.gt(alreadyAmount, reputationAmount)) {
                ApiAssert.failure("资信额度不足");
            }
            hyOrder.setTakeAmountType(4);
        }
        //现款
        if (SendTypeEnum.XK.getCode().equals(sendType)) {
            String bankLists = hyOrder.getBankLists();
            if (FlymeUtils.isNotEmpty(bankLists) && !bankLists.equals("[]")) {
                List<HyBankItem> bankItems = JsonUtils.toList(bankLists, HyBankItem.class);
                //总收取金额(含实时和认款记录)
                BigDecimal totalAmount = new BigDecimal("0");
                //总实时收取金额
                BigDecimal totalNowAmount = new BigDecimal("0");
                //总认款收取金额
                BigDecimal totalHisAmount = new BigDecimal("0");
                //账户余额
                BigDecimal goodsAmount = new BigDecimal("0");
                Boolean saveBalance = true;
                for (HyBankItem bankItem : bankItems) {
                    Integer amountType = bankItem.getAmountType();
                    ApiAssert.isNotEmpty("请选择收款方式", amountType);
                    //收款金额
                    BigDecimal takeAmount = FlymeUtils.getBigDecimal(bankItem.getTakeAmount(), "0");
                    //实时收款
                    if (amountType.equals(1)) {
                        totalNowAmount = totalNowAmount.add(takeAmount);
                        hyOrder.setBankId(bankItem.getBankId());
                        hyOrder.setTakeDate(bankItem.getTakeDate());
                        //检测收款月份是否在当月
                        checkSendDate(bankItem.getTakeDate());
                        if (FlymeUtils.gt(takeAmount, totalSaleAmount)) {
                            //@zyf@临时屏蔽
                            //ApiAssert.failure("回款金额大于发货金额,请先认款");
                        }
                    }
                    //使用认款
                    if (amountType.equals(3)) {
                        totalHisAmount = totalHisAmount.add(takeAmount);
                        hyOrder.setBankId(bankItem.getBankId());
                        hyOrder.setTakeDate(bankItem.getTakeDate());
                        saveBalance = false;
                    }
                    //余额抵扣(废弃)
                    if (amountType.equals(2)) {
                        goodsAmount = takeAmount;
                    }
                    hyOrder.setTakeAmountType(amountType);
                }
                totalAmount = totalHisAmount.add(totalNowAmount);
                hyOrder.setTakeAmount(totalAmount);
                //总货款金额
                BigDecimal totalOrderAmount = totalAmount.add(goodsAmount).add(totalDiscountAmount);
                if (FlymeUtils.lt(totalOrderAmount, totalSaleAmount)) {
                    ApiAssert.failure("货款金额不足");
                }
                if (saveBalance) {
                    BigDecimal userBalanceAmount = totalSaleAmount.subtract(totalNowAmount);
                    //如果使用账户余额则计算抵扣金额
                    if (FlymeUtils.gtzero(goodsAmount) && FlymeUtils.gtzero(userBalanceAmount)) {
                        //金额大于0表示有抵扣
                        hyOrder.setUseBalanceAmount(userBalanceAmount);
                        hyOrder.setSurplusBalanceAmount(new BigDecimal("0"));
                    }
                    if (FlymeUtils.ltzero(userBalanceAmount)) {
                        //userBalanceAmount小于0表示金额多收
                        hyOrder.setSurplusBalanceAmount(userBalanceAmount.abs());
                        hyOrder.setUseBalanceAmount(new BigDecimal("0"));
                    }
                }
            }
        }
        //资保金
        if (SendTypeEnum.ZBJ.getCode().equals(sendType)) {
            String bankLists = hyOrder.getBankLists();
            if (FlymeUtils.isNotEmpty(bankLists) && !bankLists.equals("[]")) {
                List<HyBankItem> bankItems = JsonUtils.toList(bankLists, HyBankItem.class);
                //总实时收取金额
                BigDecimal totalAmount = new BigDecimal("0");
                for (HyBankItem bankItem : bankItems) {
                    Integer amountType = bankItem.getAmountType();
                    ApiAssert.isNotEmpty("请选择收款方式", amountType);
                    BigDecimal takeAmount = FlymeUtils.getBigDecimal(bankItem.getTakeAmount(), "0");
                    if (amountType.equals(1) || amountType.equals(3)) {
                        totalAmount = totalAmount.add(takeAmount);
                        hyOrder.setBankId(bankItem.getBankId());
                        hyOrder.setTakeDate(bankItem.getTakeDate());
                    }
                    hyOrder.setTakeAmountType(amountType);
                }
                hyOrder.setTakeAmount(totalAmount);
            }
        }
        //预收款
        if (SendTypeEnum.YSK.getCode().equals(sendType)) {
            String bankLists = hyOrder.getBankLists();
            if (FlymeUtils.isNotEmpty(bankLists) && !bankLists.equals("[]")) {
                List<HyBankItem> bankItems = JsonUtils.toList(bankLists, HyBankItem.class);
                //总实时收取金额
                BigDecimal totalAmount = new BigDecimal("0");
                for (HyBankItem bankItem : bankItems) {
                    Integer amountType = bankItem.getAmountType();
                    BigDecimal takeAmount = FlymeUtils.getBigDecimal(bankItem.getTakeAmount(), "0");
                    if (amountType.equals(3)) {
                        totalAmount = totalAmount.add(takeAmount);
                        hyOrder.setBankId(bankItem.getBankId());
                        hyOrder.setTakeDate(bankItem.getTakeDate());
                        hyOrder.setTakeAmountType(3);
                    }
                }
                hyOrder.setTakeAmount(totalAmount);
            }
        }
        return saleMan;
    }

    /**
     * 检测每个月最后一天认款月份和发货月份是否在同一个月
     *
     * @param takeDate
     */
    private void checkSendDate(Date takeDate) {
        if (FlymeUtils.isNotEmpty(takeDate)) {
            //收款月份
            Integer month = takeDate.getMonth() + 1;
            String nowMonth = DateUtils.getMonth();
            if (!month.equals(Integer.parseInt(nowMonth))) {
                //@zyf@临时屏蔽
                //ApiAssert.failure("认款月份不在当月的需先认款");
            }
        }
    }

    @Override
    @DSTransactional
    @DS("master")
    public ResultBody beforeAdd(CriteriaSave cs, HyOrder hyOrder, EntityMap extra) {
        Integer historyOrder = cs.getInt("historyOrder", 0);
        Long companyId = OpenHelper.getCompanyId();
        Long userId = OpenHelper.getUserId();
        String customCode = hyOrder.getCustomCode();
        BaseUser user = userService.getById(userId);
        SysCompany company = companyService.getById(companyId);
        //获取订单号
        String orderNo = IdUtil.getSnowflake(1, 15).nextId()+"";

        ApiAssert.isNotEmpty("订单号获取失败", orderNo);
        hyOrder.setOrderId(orderNo);
        //获取订单号
        hyOrder.setOrderNo(orderNo);
        hyOrder.setCompanyId(companyId);
        hyOrder.setHostName(user.getHostName());
        //查询客户资料
        BusCustom custom = customService.selectByCustomCode(customCode, companyId);
        if (FlymeUtils.isEmpty(custom)) {
            custom = customService.syncBusCustom(company.getCompanyErpInstance(), customCode, companyId);
            ApiAssert.isNotEmpty("客户资料未同步", custom);
        }
        hyOrder.setCustomId(custom.getCustomId());
        //销售订单
        hyOrder.setOrderType(HySaleTypeEnum.CHA.getCode());
        hyOrder.setNickName(user.getNickName());
        //未提交
        hyOrder.setOrderState(CommonConstants.INT_2);
        //未提单
        hyOrder.setSendState(CommonConstants.INT_1);
        //同步状态
        hyOrder.setSyncTag(0);
        hyOrder.setPrintTag(0);
        hyOrder.setOutPrintTag(0);
        hyOrder.setOutPrintTag2(0);
        hyOrder.setRebateState(0);
        hyOrder.setProLevel(0);
        //@zyf@制单日期
        //hyOrder.setCreateDate(DateUtil.date());
        //结算系统录入(1:海鹰导入,2:结算系统录入)
        hyOrder.setSourceType(2);
        //核算状态
        hyOrder.setCalculateState(0);
        //开票员
        hyOrder.setUserId(userId);
        //订单前置校验
        BusSaleman saleMan = checkOrder(hyOrder, true, historyOrder);
        //设置订单信息
        setHyOrderInfo(hyOrder, saleMan);
        //查询订单相关提成人员
        hyOrderUtils.setSaleManInfo(hyOrder, saleMan);
        String drugList = cs.getParams("drugList");
        //保存订单明细
        saveOrderDetails(hyOrder, drugList, true);
        return super.beforeAdd(cs, hyOrder, extra);
    }

    @Override
    public ResultBody afterAdd(CriteriaSave cs, HyOrder hyOrder, EntityMap extra) {
        return super.afterAdd(cs, hyOrder, extra);
    }


    @Override
    @DSTransactional
    @DS("master")
    public ResultBody beforeEdit(CriteriaUpdate<HyOrder> cu, HyOrder hyOrder, EntityMap extra) {
        Integer historyOrder = cu.getInt("historyOrder", 0);
        //检测订单
        BusSaleman saleMan = checkOrder(hyOrder, true, historyOrder);
        setHyOrderInfo(hyOrder, saleMan);
        hyOrder.setSaleManIdF(null);
        hyOrder.setSaleManIdC(null);
        hyOrder.setSaleManIdD(null);
        hyOrder.setSaleManIdE(null);
        //修改订单需要重新核算
        hyOrder.setCalculateState(0);
        //设置订单相关结算人员
        hyOrderUtils.setSaleManInfo(hyOrder, saleMan);
        Serializable drugList = cu.get("drugList");
        if (historyOrder.equals(0)) {
            saveOrderDetails(hyOrder, drugList.toString(), false);
        }
        return super.beforeEdit(cu, hyOrder, extra);
    }


    @Override
    public ResultBody afterEdit(CriteriaUpdate cu, HyOrder hyOrder, EntityMap extra) {
        return super.afterEdit(cu, hyOrder, extra);
    }


    /**
     * 保存或者更新订单明细(2)
     *
     * @param hyOrder
     * @param drugList
     * @param isAdd
     */
    @Override
    public void saveOrderDetails(HyOrder hyOrder, String drugList, Boolean isAdd) {
        Integer sendType = hyOrder.getSendType();
        String orderId = hyOrder.getOrderId();
        Long saleManId = hyOrder.getSaleManId();
        Long companyId = hyOrder.getCompanyId();
        String customCode = hyOrder.getCustomCode();
        if (FlymeUtils.isNotEmpty(drugList) && !drugList.equals("[]")) {
            List<HyOrderItemVo> detailsList = JsonUtils.toList(drugList, HyOrderItemVo.class);
            SysCompany company = companyService.getById(hyOrder.getCompanyId());
            String dbName = company.getBusinessScope();
            ApiAssert.isNotEmpty("数据库示例未配置", dbName);
            Long userId = OpenHelper.getUserId();
            BaseUser user = userService.getById(userId);
            Integer syncTag = FlymeUtils.getInteger(hyOrder.getSyncTag(), 0);
            if (FlymeUtils.isNotEmpty(detailsList)) {
                //资保金总金额
                BigDecimal totalCustomBond = new BigDecimal("0");
                //总销售金额
                BigDecimal totalSaleAmount = hyOrder.getTotalSaleAmount();
                Boolean costPriceTag = true;
                for (HyOrderItemVo hyOrderItem : detailsList) {
                    //商品ID
                    String drugName = hyOrderItem.getDrugsName();
                    String drugsSpec = hyOrderItem.getDrugsSpec();
                    //商品编号
                    String drugNo = hyOrderItem.getDrugNo();
                    String drugType = hyOrderItem.getDrugType();
                    //库存编码
                    Integer drugLogId = hyOrderItem.getDrugLotId();
                    //成本价
                    BigDecimal costPrice = FlymeUtils.getBigDecimal(hyOrderItem.getCostPrice(), "0");
                    //销售数量
                    BigDecimal saleNum = FlymeUtils.getBigDecimal(hyOrderItem.getSaleNum(), "0");
                    BigDecimal salePrice = FlymeUtils.getBigDecimal(hyOrderItem.getSalePrice(), "0");
                    BigDecimal saleAmount = salePrice.multiply(saleNum);
                    BigDecimal costAmount = costPrice.multiply(saleNum);
                    String orderDetailsId = hyOrderItem.getOrderDetailsId();
                    HyOrderDetail hyOrderDetail = hyOrderDetailService.getById(orderDetailsId);
                    if (FlymeUtils.isEmpty(orderDetailsId)) {
                        hyOrderDetail = new HyOrderDetail();
                        hyOrderDetail.setOrderDetailsId(IdWorker.getIdStr());
                        hyOrderDetail.setHostName(user.getHostName());
                        initBusOrderDetails(hyOrder, hyOrderDetail);
                    }
                    if (costPrice.equals(new BigDecimal("0"))) {
                        //costPrice = hyRemoteOrderService.selectCostPrice(dbName,orderDetailsId.toString());
                    }
                    hyOrderDetail.setCalculateState(0);
                    hyOrderDetail.setSaleManId(hyOrder.getSaleManId());
                    hyOrderDetail.setSaleManIdD(hyOrder.getSaleManIdD());
                    hyOrderDetail.setSaleManIdC(hyOrder.getSaleManIdC());
                    hyOrderDetail.setSaleManIdE(hyOrder.getSaleManIdE());
                    hyOrderDetail.setSaleManIdF(hyOrder.getSaleManIdF());
                    hyOrderDetail.setSaleNum(saleNum);
                    //票折金额
                    hyOrderDetail.setDiscountPrice(hyOrderItem.getDiscountPrice());
                    hyOrderDetail.setSaleAmount(saleAmount);
                    hyOrderDetail.setSurplusNum(hyOrderItem.getSurplusNum());
                    hyOrderDetail.setSalePrice(salePrice);
                    hyOrderDetail.setCostPrice(costPrice);

                    hyOrderDetail.setDeptId(hyOrder.getDeptId());
                    hyOrderDetail.setCustomCode(hyOrder.getCustomCode());
                    hyOrderDetail.setCustomId(hyOrder.getCustomId());
                    hyOrderDetail.setSendDate(hyOrder.getSendDate());
                    hyOrderDetail.setSendYear(Integer.parseInt(DateUtils.getYear()));
                    hyOrderDetail.setSendMonth(Integer.parseInt(DateUtils.getMonth()));
                    hyOrderDetail.setSendDay(Integer.parseInt(DateUtils.getDay()));
                    hyOrderDetail.setDrugNo(drugNo);
                    hyOrderDetail.setDrugLotNo(hyOrderItem.getDrugLotNo());
                    hyOrderDetail.setDrugLotId(drugLogId);
                    hyOrderDetail.setStoreCode(hyOrderItem.getStoreCode());
                    hyOrderDetail.setStoreName(hyOrderItem.getStoreName());
                    hyOrderDetail.setDrugsName(drugName);
                    hyOrderDetail.setDrugsSpec(drugsSpec);
                    hyOrderDetail.setDrugType(drugType);
                    hyOrderDetail.setRebateAmount(new BigDecimal("0"));
                    hyOrderDetail.setSettleRebateAmount(new BigDecimal("0"));
                    hyOrderDetail.setProducersName(hyOrderItem.getProducersName());
                    //有效期
                    hyOrderDetail.setExpirationDate(hyOrderItem.getExpirationDate());
                    hyOrderDetail.setGenerationDate(hyOrderItem.getGenerationDate());
                    //件容
                    Integer drugJr = FlymeUtils.getInteger(hyOrderItem.getDrugJr(), 0);
                    //件数
                    BigDecimal drugsJs = new BigDecimal("0");
                    if (drugJr > 0) {
                        drugsJs = saleNum.divide(new BigDecimal(drugJr), 4, BigDecimal.ROUND_HALF_UP);
                    }
                    hyOrderDetail.setDrugJs(drugsJs);
                    hyOrderDetail.setPrintDrugJs(drugsJs);
                    hyOrderDetail.setDrugJr(drugJr);
                    //计算费用
                    hyOrderUtils.computeFee(hyOrder, hyOrderDetail, false, false);
                    //资保金金额
                    BigDecimal customBond = FlymeUtils.getBigDecimal(hyOrderDetail.getCustomBond(), "0");
                    //资保金应收总金额
                    totalCustomBond = totalCustomBond.add(customBond);
                    if (SendTypeEnum.ZBJ.getCode().equals(sendType)) {
                        hyOrderDetail.setCustomReturnState(0);
                    }
                    //保存或更新订单明细
                    hyOrderDetailService.saveOrUpdate(hyOrderDetail);
                    //票折金额
                    BigDecimal discountPrice = FlymeUtils.getBigDecimal(hyOrderDetail.getDiscountPrice(), "0");
                    if (FlymeUtils.gtzero(discountPrice)) {
                        //添加票折明细
                        hyOrderDetailService.addDiscountDetails(hyOrderDetail, hyOrder, discountPrice);
                    }

                }
                if (FlymeUtils.isNotEmpty(sendType)) {
                    hyOrder.setOrderState(0);
                }

                //资保金收款方式
                if (SendTypeEnum.ZBJ.getCode().equals(sendType)) {
                    String bankLists = hyOrder.getBankLists();
                    hyOrder.setTotalBondAmount(totalCustomBond);
                    if (checkBankLists(bankLists)) {
                        List<HyBankItem> bankItems = JsonUtils.toList(bankLists, HyBankItem.class);
                        //实时收取金额
                        BigDecimal totalBankAmount = new BigDecimal("0");
                        Boolean useBalance = false;
                        for (HyBankItem bankItem : bankItems) {
                            Integer amountType = bankItem.getAmountType();
                            if (amountType.equals(2)) {
                                useBalance = true;
                            }
                        }
                        //资保金余额(不含当前订单金额)
                        BigDecimal surplusCustomBondAmount = saleManService.surplusCustomBondAmount(saleManId, companyId, hyOrder.getOrderId());
                        if (useBalance) {
                            totalBankAmount = totalBankAmount.add(surplusCustomBondAmount);
                        }
                        if (FlymeUtils.lt(totalBankAmount, totalCustomBond)) {
                            //ApiAssert.failure("资保金金额不足,资保金应收金额:"+totalCustomBond);
                        }
                    }
                }
                //保存认款使用记录
                saveBusPaymentOrder(hyOrder);
            }
        }
    }


    /**
     * 保存认款使用记录
     *
     * @param order
     */
    private void saveBusPaymentOrder(HyOrder order) {
        String orderId = order.getOrderId();
        String banksList = order.getBankLists();
        //发货方式
        Integer sendType = order.getSendType();
        //总金额
        BigDecimal totalAmount = order.getTotalSaleAmount();
        if (!SendTypeEnum.QZ.getCode().equals(sendType)) {
            if (SendTypeEnum.ZBJ.getCode().equals(sendType)) {
                //资保金方式时取资保金应收金额
                totalAmount = order.getTotalBondAmount();
            }
            if (checkBankLists(banksList)) {
                List<HyBankItem> bankItems = JsonUtils.toList(banksList, HyBankItem.class);
                //先使用认款记录(按amountType排序)
                bankItems = bankItems.stream().sorted(Comparator.comparing(HyBankItem::getAmountType).reversed()).collect(Collectors.toList());
                if (FlymeUtils.isNotEmpty(bankItems)) {
                    List<BusPaymentOrder> busPaymentOrderList = new ArrayList<>();
                    for (HyBankItem bankItem : bankItems) {
                        Integer amountType = bankItem.getAmountType();
                        //实时收取或认款记录
                        if (amountType.equals(1) || amountType.equals(3)) {
                            String bankStatementId = bankItem.getBankStatementId();
                            ApiAssert.isNotEmpty("银行流水不存在", bankStatementId);
                            BusBankStatement bankStatement = bankStatementService.getById(bankStatementId);
                            //认款金额
                            BigDecimal amount = FlymeUtils.getBigDecimal(bankItem.getTakeAmount(), "0");
                            BusPaymentOrder paymentOrder = paymentOrderService.getById(bankItem.getPaymentOrderId());
                            if (FlymeUtils.isEmpty(paymentOrder)) {
                                paymentOrder = new BusPaymentOrder();
                            }
                            BusPayment payment = null;
                            //实时收款
                            if (amountType.equals(1)) {
                                //添加全款认款单
                                if (SendTypeEnum.XK.getCode().equals(sendType)) {
                                    payment = paymentService.addOrderPayment(order, bankItem);
                                }
                                //添加资保金认款单
                                if (SendTypeEnum.ZBJ.getCode().equals(sendType)) {
                                    payment = paymentService.addCustomBondPayment(order, bankItem);
                                }
                            }
                            //认款记录
                            if (amountType.equals(3)) {
                                Long paymentId = bankItem.getPaymentId();
                                ApiAssert.isNotEmpty("认款ID不存在", paymentId);
                                payment = paymentService.getById(paymentId);
                                paymentOrder.setPaymentId(paymentId);
                            }
                            if (FlymeUtils.isNotEmpty(payment)) {
                                paymentOrder.setPaymentId(payment.getPaymentId());
                                paymentOrder.setPaymentNo(payment.getPaymentNo());
                                paymentOrder.setBankName(payment.getBankName());
                                paymentOrder.setRenDate(payment.getRenDate());
                            }
                            paymentOrder.setBankId(bankItem.getBankId());
                            paymentOrder.setTakeDate(bankItem.getTakeDate());
                            paymentOrder.setOrderId(orderId);
                            paymentOrder.setCompanyId(order.getCompanyId());
                            paymentOrder.setBankStatementId(bankStatementId);
                            paymentOrder.setTakeAmount(bankStatement.getAmount());
                            paymentOrder.setAmountType(bankItem.getAmountType());
                            paymentOrder.setSendType(order.getSendType());
                            paymentOrder.setCustomId(String.valueOf(order.getCustomId()));
                            totalAmount = totalAmount.subtract(amount);
                            if (FlymeUtils.ge(totalAmount, new BigDecimal("0"))) {
                                paymentOrder.setUseAmount(amount);
                                paymentOrder.setSurplusAmount(new BigDecimal("0"));
                                busPaymentOrderList.add(paymentOrder);
                            }
                            if (FlymeUtils.ltzero(totalAmount)) {
                                BigDecimal userAmount = bankItem.getTakeAmount().add(totalAmount);
                                paymentOrder.setUseAmount(userAmount);
                                paymentOrder.setSurplusAmount(totalAmount.abs());
                                busPaymentOrderList.add(paymentOrder);
                                break;
                            }
                        }
                    }
                    if (FlymeUtils.isNotEmpty(busPaymentOrderList)) {
                        //保存使用记录
                        paymentOrderService.saveOrUpdateBatch(busPaymentOrderList);
                    }
                }
            }
        }
    }


    private Boolean checkBankLists(String bankLists) {
        return FlymeUtils.isNotEmpty(bankLists) && !bankLists.equals("[]");
    }

    @Override
    public HyOrder getByOrderNo(String orderNo) {
        CriteriaQuery cq = new CriteriaQuery<>(HyOrder.class);
        cq.eq("orderNo", orderNo);
        return getOne(cq, false);
    }

    @Override
    public HyOrder getOutOrderNo(String orderNo,Long companyId) {
        CriteriaQuery cq = new CriteriaQuery<>(HyOrder.class);
        cq.eq("outOrderNo", orderNo);
        cq.eq("companyId", companyId);
        return getOne(cq, false);
    }

    @Override
    public List<HyOrder> getBackOrder(String orderId) {
        CriteriaQuery cq = new CriteriaQuery<>(HyOrder.class);
        cq.eq("parentId", orderId);
        return list(cq);
    }

    @Override
    public EntityMap getMapByOrderId(String orderId) {
        CriteriaQuery cq = new CriteriaQuery(HyOrder.class);
        cq.select(HyOrder.class, "*");
        cq.select(BusCustom.class, "customName");
        cq.select(BusDept.class, "deptName", "deptType");
        cq.eq(HyOrder.class, "orderId", orderId);
        cq.createJoin(BusCustom.class);
        cq.createJoin(BusDept.class);
        return findOne(cq);
    }

    @Override
    public Boolean updateOrderState(Serializable orderId, String processInstanceId, Integer orderState, Integer revokeState, Integer syncTag, Date createDate) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "orderState", orderState);
        cu.set(true, "revokeState", revokeState);
        cu.set(true, "processInstanceId", processInstanceId);
        cu.set(true, "syncTag", syncTag);
        cu.set(true, "createDate", createDate);
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public Boolean updateOrderState(Serializable orderId, String processInstanceId, Integer orderState, Integer revokeState, Integer syncTag) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "orderState", orderState);
        cu.set(true, "revokeState", revokeState);
        cu.set(true, "processInstanceId", processInstanceId);
        cu.set(true, "syncTag", syncTag);
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }


    private Boolean updateSyncTag(Serializable orderId, Integer syncTag) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "syncTag", syncTag);
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public Boolean updateOrderState(Serializable orderId, Integer orderState) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "orderState", orderState);
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public Boolean revokeProcess(String orderId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "revokeState", CommonConstants.INT_1);
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public Boolean deleteBackOrder(String orderId, String parentId) {
        //删除订单明细
        hyOrderDetailService.delByOrderId(orderId);
        hyorderReturnService.deleteByOrderId(orderId);
        removeById(orderId);
        List<BusPaymentOrder> paymentOrderList = paymentOrderService.selectByOrderId(orderId);
        if (FlymeUtils.isNotEmpty(paymentOrderList)) {
            for (BusPaymentOrder paymentOrder : paymentOrderList) {
                Long paymentId = paymentOrder.getPaymentId();
                //退货金额
                BigDecimal useAmount = paymentOrder.getUseAmount();
                paymentService.addSurplusAmount(paymentId, useAmount);
            }
            paymentOrderService.removeByOrderId(orderId);
        }
        return true;
    }

    @Override
    public Boolean syncSendState() {
        List<HyOrder> orderList = selectBySendState(CommonConstants.INT_0);
        if (FlymeUtils.isNotEmpty(orderList)) {
            for (HyOrder order : orderList) {
                String orderType = order.getOrderType();
                Long companyId = order.getCompanyId();
                String companyErpInstance = businessUtils.getDbName(companyId);
                String orderId = order.getOrderId();
                Map outOrderMap = null;
                if (HySaleTypeEnum.CHA.getCode().equals(orderType)) {
                    outOrderMap = hyRemoteOrderService.getOutOrderNo(companyErpInstance, orderId);
                    if (FlymeUtils.isNotEmpty(outOrderMap)) {
                        outOrderMap.put("backTag", 0);
                    }
                }
                if (HySaleTypeEnum.CHC.getCode().equals(orderType)) {
                    outOrderMap = hyRemoteOrderService.getCkjOutOrderNo(companyErpInstance, orderId);
                    if (FlymeUtils.isNotEmpty(outOrderMap)) {
                        outOrderMap.put("backTag", 1);
                    }
                }
                if (FlymeUtils.isNotEmpty(outOrderMap)) {
                    updateSendState(orderId, outOrderMap);
                }
            }
        }
        return true;
    }

    @Override
    public Boolean syncInsertOrder() {
        //查询未同步订单
        List<HyOrder> orderList = selectByApplyedOrder();
        if (FlymeUtils.isNotEmpty(orderList)) {
            for (HyOrder order : orderList) {
                Long companyId = order.getCompanyId();
                String orderId = order.getOrderId();
                Integer sendType = order.getSendType();
                Integer sendState = FlymeUtils.getInteger(order.getSendState(), 0);
                Integer syncTag = FlymeUtils.getInteger(order.getSyncTag(), 0);
                boolean tag = false;
                //商务部审核意见
                String commentsSw = order.getCommentsSw();
                //销售部审核意见
                String commentsSx = order.getCommentsXs();
                //财务审核意见
                String commentsCw = order.getCommentsCw();
                if (FlymeUtils.allNotNull(commentsSw, commentsCw, commentsSx)) {
                    String[] commentsSwArray = commentsSw.split("#");
                    //商务审核人
                    String nickNameSw = commentsSwArray[0];
                    //商务审核时间
                    String approveDateSw = commentsSwArray[1];
                    //审批意见
                    String commentsSwStr = commentsSwArray[2];
                    //未同步且发货
                    if (syncTag.equals(0) && sendState.equals(0)) {
                        //同步订单到海鹰系统出订单主,出订单细表中 更新海鹰系统商品库存 在单数，可开票数
                        List<EntityMap> orderDetailsList = hyOrderDetailService.selectByOrderId(orderId, HySaleTypeEnum.CHA);
                        if (FlymeUtils.isNotEmpty(orderDetailsList)) {
                            //合计数量
                            BigDecimal totalSaleNum = new BigDecimal("0");
                            //合计无税金额
                            BigDecimal totalCostAmount = new BigDecimal("0");
                            //合计含税金额
                            BigDecimal totalSaleAmount = new BigDecimal("0");
                            SysCompany company = companyService.getById(companyId.toString());
                            String dbName = businessUtils.getDbName(companyId);
                            ApiAssert.isNotEmpty("账套实例未配置", dbName);
                            try {
                                //添加订单明细
                                int i = 1;
                                for (EntityMap hyOrderDetail : orderDetailsList) {
                                    BigDecimal saleAmount = hyOrderDetail.getBigDecimal("saleAmount");
                                    BigDecimal costAmount = hyOrderDetail.getBigDecimal("costAmount");
                                    BigDecimal saleNum = hyOrderDetail.getBigDecimal("saleNum");
                                    BigDecimal drugJs = hyOrderDetail.getBigDecimal("drugJs");
                                    totalSaleNum = totalSaleNum.add(saleNum);
                                    totalCostAmount = totalCostAmount.add(costAmount);
                                    totalSaleAmount = totalSaleAmount.add(saleAmount);
                                    BigDecimal mlAmount = saleAmount.subtract(costAmount);
                                    String orderDetailsId = hyOrderDetail.get("orderDetailsId");
                                    String drugNo = hyOrderDetail.get("drugNo");
                                    String drugLotNo = hyOrderDetail.get("drugLotNo");
                                    String storeCode = hyOrderDetail.get("storeCode");
                                    hyOrderDetail.put("orderDetailsId", orderId);
                                    hyOrderDetail.put("userCode", orderDetailsId);
                                    hyOrderDetail.put("sendDate", order.getCreateDate());
                                    hyOrderDetail.put("callOrderDetailsNo", "");
                                    hyOrderDetail.put("mlAmount", mlAmount);
                                    hyOrderDetail.put("remark", "");
                                    hyOrderDetail.put("detailsIndex", i);
                                    i++;
                                    hyRemoteOrderService.insertHyOrderDetails(dbName, hyOrderDetail);
                                }
                                //添加订单
                                //合计毛利
                                BigDecimal totalMlAmount = totalSaleAmount.subtract(totalCostAmount);
                                EntityMap entity = new EntityMap();
                                entity.put("orderId", order.getOrderId());
                                entity.put("outStoreType", "CHA");
                                entity.put("customCode", order.getCustomCode());
                                entity.put("businessCode", order.getBusinessCode());
                                entity.put("deptNo", order.getHyDeptNo());
                                entity.put("nickName", order.getNickName());
                                entity.put("totalSaleNum", totalSaleNum);
                                entity.put("totalCostAmount", totalCostAmount);
                                entity.put("totalSaleAmount", totalSaleAmount);
                                entity.put("totalMlAmount", totalMlAmount);
                                entity.put("callOrderNo", "");
                                entity.put("callOrderType", "");
                                entity.put("companyName", company.getCompanyName());
                                entity.put("customAddress", order.getCustomAddress());
                                entity.put("customUserName", order.getCustomUserName());
                                entity.put("customUserTel", order.getCustomUserTel());
                                entity.put("createTime", order.getCreateTime());
                                Date sendDate = order.getCreateDate();
                                entity.put("createTime", order.getCreateTime());
                                entity.put("sendDate", sendDate);
                                entity.put("remark", order.getRemark());
                                entity.put("commentsSx", commentsSx);
                                entity.put("commentsSw", commentsSwStr);
                                entity.put("nickNameSw", nickNameSw);
                                entity.put("approveDateSw", approveDateSw);
                                entity.put("commentsCw", commentsCw);
                                hyRemoteOrderService.insertHyOrder(dbName, entity);
                                tag = true;
                            } catch (Exception ex) {
                                log.error("#################订单保存异常#############订单编号:" + order.getOrderId());
                                ex.printStackTrace();
                            }
                        }
                    }
                }
                if (tag) {
                    //更新同步状态
                    updateSyncTag(orderId, 1);
                }
            }
        }
        return true;
    }

    @Override
    public Boolean syncBackOrder() {
        //查询未同步订单
        List<HyOrder> orderList = selectByApplyedBackOrder();
        if (FlymeUtils.isNotEmpty(orderList)) {
            for (HyOrder order : orderList) {
                String orderId = order.getOrderId();
                Long companyId = order.getCompanyId();
                Integer syncTag = FlymeUtils.getInteger(order.getSyncTag(), 0);
                boolean tag = false;
                //销售部审核意见
                String commentsSx = order.getCommentsXs();
                //质管审核意见
                String commentsSw = order.getCommentsSw();
                //财务审核意见
                String commentsCw = order.getCommentsCw();
                //退货状态(0未收货,已收货)
                Integer sendState = FlymeUtils.getInteger(order.getSendState(), 0);
                if (FlymeUtils.allNotNull(commentsCw, commentsCw, commentsSx)) {
                    if (syncTag.equals(0) && sendState.equals(0)) {
                        //同步订单到海鹰系统出订单主,出订单细表中
                        List<EntityMap> orderDetailsList = hyOrderDetailService.selectByOrderId(orderId, HySaleTypeEnum.CHC);
                        ApiAssert.isNotEmpty("订单明细不存在", orderDetailsList);
                        if (FlymeUtils.isNotEmpty(orderDetailsList)) {
                            //合计数量
                            BigDecimal totalSaleNum = new BigDecimal("0");
                            //合计无税金额
                            BigDecimal totalCostAmount = new BigDecimal("0");
                            //合计含税金额
                            BigDecimal totalSaleAmount = new BigDecimal("0");
                            SysCompany company = companyService.getById(companyId.toString());
                            String dbName = company.getBusinessScope();
                            ApiAssert.isNotEmpty("账套实例未配置", dbName);
                            try {
                                int i = 1;
                                //添加退货明细
                                for (EntityMap hyOrderDetail : orderDetailsList) {
                                    BigDecimal saleAmount = hyOrderDetail.getBigDecimal("saleAmount");
                                    BigDecimal costAmount = hyOrderDetail.getBigDecimal("costAmount");
                                    BigDecimal saleNum = hyOrderDetail.getBigDecimal("saleNum");
                                    String orderDetailsId = hyOrderDetail.get("orderDetailsId");
                                    String parentId = hyOrderDetail.get("parentId");
                                    String reason = hyOrderDetail.get("reason");
                                    totalSaleNum = totalSaleNum.add(saleNum);
                                    totalCostAmount = totalCostAmount.add(costAmount);
                                    totalSaleAmount = totalSaleAmount.add(saleAmount);
                                    BigDecimal mlAmount = saleAmount.subtract(costAmount);
                                    hyOrderDetail.put("orderDetailsId", orderId);
                                    hyOrderDetail.put("userCode", orderDetailsId);
                                    hyOrderDetail.put("sendDate", order.getCreateDate());
                                    hyOrderDetail.put("callOrderDetailsNo", parentId);
                                    hyOrderDetail.put("remark", reason);
                                    hyOrderDetail.put("mlAmount", mlAmount);
                                    hyOrderDetail.put("detailsIndex", i);
                                    i++;
                                    hyRemoteOrderService.insertHyOrderDetails(dbName, hyOrderDetail);
                                }
                                //添加退货通知单
                                //合计毛利
                                BigDecimal totalMlAmount = totalSaleAmount.subtract(totalCostAmount);
                                Date createDate = order.getCreateDate();
                                EntityMap entity = new EntityMap();
                                entity.put("orderId", order.getOrderId());
                                entity.put("outStoreType", HySaleTypeEnum.CHC.getCode());
                                entity.put("customCode", order.getCustomCode());
                                entity.put("businessCode", order.getBusinessCode());
                                entity.put("deptNo", order.getHyDeptNo());
                                entity.put("nickName", order.getNickName());
                                entity.put("totalSaleNum", totalSaleNum);
                                entity.put("totalCostAmount", totalCostAmount);
                                entity.put("totalSaleAmount", totalSaleAmount);
                                entity.put("totalMlAmount", totalMlAmount);
                                entity.put("callOrderNo", order.getParentId());
                                entity.put("callOrderType", HySaleTypeEnum.CHA.getCode());
                                entity.put("companyName", company.getCompanyName());
                                entity.put("customAddress", order.getCustomAddress());
                                entity.put("customUserName", order.getCustomUserName());
                                entity.put("customUserTel", order.getCustomUserTel());
                                entity.put("createTime", order.getCreateTime());
                                entity.put("commentsSx", order.getCommentsXs());
                                entity.put("commentsSw", order.getCommentsSw());
                                entity.put("commentsCw", order.getCommentsCw());
                                entity.put("createDate", createDate);
                                entity.put("remark", order.getRemark());
                                hyRemoteOrderService.insertHyBackOrder(dbName, entity);
                                tag = true;
                            } catch (Exception ex) {
                                log.error("#################订单保存异常#############订单编号:" + order.getOrderId());
                                ex.printStackTrace();
                            }
                        }

                        if (tag) {
                            //更新同步状态
                            updateSyncTag(orderId, 1);
                        }
                    }
                }
            }
        }
        return true;
    }

    @Override
    public Boolean saveTuibu(String orderId, String drugList) {
        return true;
    }


    @Override
    public Boolean saveBack(String orderId, String reason, String returnList) {
        HyOrder backOrder = initBackOrder(orderId);
        List<EntityMap> list = JsonUtils.toList(returnList, EntityMap.class);
        BigDecimal totalSaleAmount = new BigDecimal("0");
        BigDecimal totalCustomBond = new BigDecimal("0");
        List<BusHyorderReturn> hyorderReturns = new ArrayList<>();
        //添加退货回款信息
        if (FlymeUtils.isNotEmpty(list)) {
            Boolean hasReturn = false;
            for (EntityMap entityMap : list) {
                Long orderDetailsReturnId = entityMap.getLong("orderDetailsReturnId");
                String orderDetailsId = entityMap.get("orderDetailsId");
                BigDecimal saleNum = entityMap.getBigDecimal("saleNum");
                BigDecimal backNum = entityMap.getBigDecimal("backNum").multiply(new BigDecimal("-1"));
                BigDecimal radio = backNum.divide(saleNum, 5, BigDecimal.ROUND_HALF_UP);
                if (FlymeUtils.isNotEmpty(orderDetailsReturnId)) {
                    BusHyorderReturn hyorderReturn = hyorderReturnService.getById(orderDetailsReturnId);
                    BigDecimal salePrice = hyorderReturn.getSalePrice();
                    BigDecimal costPrice = FlymeUtils.getBigDecimal(hyorderReturn.getCostPrice(), "0");
                    BigDecimal settlePrice = FlymeUtils.getBigDecimal(hyorderReturn.getSettlePrice(), "0");
                    hyorderReturnService.computeAmount(hyorderReturn, radio);
                    hyorderReturn.setSaleNum(backNum);
                    hyorderReturn.setSaleAmount(salePrice.multiply(backNum));
                    hyorderReturn.setSettleSendAmount(settlePrice.multiply(backNum));
                    hyorderReturn.setCostAmount(costPrice.multiply(backNum));
                    hyorderReturn.setReturnAmount(backNum.multiply(salePrice));
                    hyorderReturn.setParentId(orderDetailsReturnId + "");
                    hyorderReturn.setOrderId(backOrder.getOrderId());
                    hyorderReturn.setSaleType(HySaleTypeEnum.CHC.getCode());
                    hyorderReturn.setOrderDetailsReturnId(IdWorker.getId());
                    hyorderReturn.setOverDateAmount(new BigDecimal("0"));
                    hyorderReturn.setDeptSettleApplyId(null);
                    hyorderReturn.setSettleApplyId(null);
                    hyorderReturn.setSettleApplyIdC(null);
                    hyorderReturn.setSettleApplyIdD(null);
                    hyorderReturn.setSettleApplyIdE(null);
                    hyorderReturn.setUpdateTime(null);
                    hyorderReturn.setCreateTime(DateUtils.getNowDateTime());
                    hyorderReturnService.save(hyorderReturn);
                    totalSaleAmount = totalSaleAmount.add(hyorderReturn.getSaleAmount());
                    totalCustomBond = totalCustomBond.add(hyorderReturn.getCustomBond());
                    hasReturn = true;
                    hyorderReturns.add(hyorderReturn);
                } else {
                    HyOrderDetail hyOrderDetail = hyOrderDetailService.getById(orderDetailsId);
                    BigDecimal salePrice = FlymeUtils.getBigDecimal(hyOrderDetail.getSalePrice(), "0");
                    BigDecimal costPrice = FlymeUtils.getBigDecimal(hyOrderDetail.getCostPrice(), "0");
                    BigDecimal settlePrice = FlymeUtils.getBigDecimal(hyOrderDetail.getSettlePrice(), "0");
                    //添加退货明细
                    HyOrderDetail save = addBackOrderDetails2(backOrder, hyOrderDetail, backNum, reason, true);
                    BusHyorderReturn orderReturn = new BusHyorderReturn();
                    BeanUtils.copyProperties(hyOrderDetail, orderReturn);
                    hyorderReturnService.computeAmount(orderReturn, radio);
                    orderReturn.setSaleNum(backNum);
                    orderReturn.setSaleAmount(salePrice.multiply(backNum));
                    orderReturn.setCostAmount(costPrice.multiply(backNum));
                    orderReturn.setSettleSendAmount(settlePrice.multiply(backNum));
                    orderReturn.setOrderDetailsReturnId(IdWorker.getId());
                    orderReturn.setSaleType(HySaleTypeEnum.CHC.getCode());
                    orderReturn.setOverDateAmount(new BigDecimal("0"));
                    orderReturn.setOrderId(backOrder.getOrderId());
                    orderReturn.setParentId(hyOrderDetail.getOrderDetailsId());
                    orderReturn.setCreateTime(DateUtils.getNowDateTime());
                    orderReturn.setDeptSettleApplyId(null);
                    orderReturn.setUpdateTime(null);
                    totalSaleAmount = totalSaleAmount.add(orderReturn.getSaleAmount());
                    totalCustomBond = totalCustomBond.add(orderReturn.getCustomBond());
                    hyorderReturnService.save(orderReturn);
                    hyOrderDetailService.saveOrUpdate(save);
                }
            }
            if (hasReturn) {
                Map<String, List<BusHyorderReturn>> orderDetailsList = hyorderReturns.stream().collect(Collectors.groupingBy(BusHyorderReturn::getOrderDetailsId));
                if (FlymeUtils.isNotEmpty(orderDetailsList)) {
                    orderDetailsList.forEach((key, value) -> {
                        List<BusHyorderReturn> item = value;
                        BigDecimal totalBackNum = new BigDecimal("0");
                        BigDecimal totalAmount = new BigDecimal("0");
                        BigDecimal totalSettleAmount = new BigDecimal("0");
                        BigDecimal totalSettleAmountD = new BigDecimal("0");
                        BigDecimal totalSettleAmountE = new BigDecimal("0");
                        BigDecimal totalSettleAmountC = new BigDecimal("0");
                        BigDecimal totalSettleRebateAmount = new BigDecimal("0");
                        BigDecimal totalDeptSettleAmount = new BigDecimal("0");
                        BigDecimal totalDeptProfitAmount = new BigDecimal("0");
                        BigDecimal totalSettleSendAmount = new BigDecimal("0");
                        BigDecimal totalPayInvoiceTaxAmount = new BigDecimal("0");
                        BigDecimal totalYtTaxAmount = new BigDecimal("0");
                        BigDecimal totalCheckAmount = new BigDecimal("0");
                        BigDecimal totalBjProfitAmount = new BigDecimal("0");
                        BigDecimal totalDrugProfitAmount = new BigDecimal("0");
                        BigDecimal totalOverStandAmount = new BigDecimal("0");
                        BigDecimal totalTaxRateDiff = new BigDecimal("0");
                        BigDecimal totalTaxProfitAmount = new BigDecimal("0");
                        BigDecimal totalProfitAmount = new BigDecimal("0");
                        BigDecimal totalDeptSettleOverAmount = new BigDecimal("0");
                        BigDecimal totalRebateAmount = new BigDecimal("0");
                        BigDecimal totalOverDateAmount = new BigDecimal("0");
                        for (BusHyorderReturn hyorderReturn : item) {
                            BigDecimal backNum = FlymeUtils.getBigDecimal(hyorderReturn.getSaleNum(), "0");
                            BigDecimal saleAmount = FlymeUtils.getBigDecimal(hyorderReturn.getSaleAmount(), "0");
                            BigDecimal settleAmount = FlymeUtils.getBigDecimal(hyorderReturn.getSettleAmount(), "0");
                            BigDecimal settleAmountD = FlymeUtils.getBigDecimal(hyorderReturn.getSettleAmountD(), "0");
                            BigDecimal settleAmountE = FlymeUtils.getBigDecimal(hyorderReturn.getSettleAmountE(), "0");
                            BigDecimal settleAmountC = FlymeUtils.getBigDecimal(hyorderReturn.getSettleAmountC(), "0");
                            BigDecimal settleRebateAmount = FlymeUtils.getBigDecimal(hyorderReturn.getSettleRebateAmount(), "0");
                            BigDecimal deptSettleAmount = FlymeUtils.getBigDecimal(hyorderReturn.getDeptSettleAmount(), "0");
                            BigDecimal deptProfitAmount = FlymeUtils.getBigDecimal(hyorderReturn.getDeptProfitAmount(), "0");
                            BigDecimal settleSendAmount = FlymeUtils.getBigDecimal(hyorderReturn.getSettleSendAmount(), "0");
                            BigDecimal payInvoiceTaxAmount = FlymeUtils.getBigDecimal(hyorderReturn.getPayInvoiceTaxAmount(), "0");
                            BigDecimal ytTaxAmount = FlymeUtils.getBigDecimal(hyorderReturn.getYtTaxAmount(), "0");
                            BigDecimal checkAmount = FlymeUtils.getBigDecimal(hyorderReturn.getCheckAmount(), "0");
                            BigDecimal bjProfitAmount = FlymeUtils.getBigDecimal(hyorderReturn.getBjProfitAmount(), "0");
                            BigDecimal drugProfitAmount = FlymeUtils.getBigDecimal(hyorderReturn.getDrugProfitAmount(), "0");
                            BigDecimal overStandAmount = FlymeUtils.getBigDecimal(hyorderReturn.getOverStandAmount(), "0");
                            BigDecimal taxRateDiff = FlymeUtils.getBigDecimal(hyorderReturn.getTaxRateDiff(), "0");
                            BigDecimal taxProfitAmount = FlymeUtils.getBigDecimal(hyorderReturn.getTaxProfitAmount(), "0");
                            BigDecimal profitAmount = FlymeUtils.getBigDecimal(hyorderReturn.getProfitAmount(), "0");
                            BigDecimal deptSettleOverAmount = FlymeUtils.getBigDecimal(hyorderReturn.getDeptSettleOverAmount(), "0");
                            BigDecimal rebateAmount = FlymeUtils.getBigDecimal(hyorderReturn.getRebateAmount(), "0");
                            BigDecimal overDateAmount = FlymeUtils.getBigDecimal(hyorderReturn.getOverDateAmount(), "0");
                            totalBackNum = totalBackNum.add(backNum);
                            totalAmount = totalAmount.add(saleAmount);
                            totalSettleSendAmount = totalSettleSendAmount.add(settleSendAmount);
                            totalDeptProfitAmount = totalDeptProfitAmount.add(deptProfitAmount);
                            totalDeptSettleAmount = totalDeptSettleAmount.add(deptSettleAmount);
                            totalSettleRebateAmount = totalSettleRebateAmount.add(settleRebateAmount);
                            totalSettleAmountC = totalSettleAmountC.add(settleAmountC);
                            totalSettleAmountD = totalSettleAmountD.add(settleAmountD);
                            totalSettleAmount = totalSettleAmount.add(settleAmount);
                            totalSettleAmountE = totalSettleAmountE.add(settleAmountE);
                            totalPayInvoiceTaxAmount = totalPayInvoiceTaxAmount.add(payInvoiceTaxAmount);
                            totalYtTaxAmount = totalYtTaxAmount.add(ytTaxAmount);
                            totalCheckAmount = totalCheckAmount.add(checkAmount);
                            totalBjProfitAmount = totalBjProfitAmount.add(bjProfitAmount);
                            totalDrugProfitAmount = totalDrugProfitAmount.add(drugProfitAmount);
                            totalOverStandAmount = totalOverStandAmount.add(overStandAmount);
                            totalTaxRateDiff = totalTaxRateDiff.add(taxRateDiff);
                            totalTaxProfitAmount = totalTaxProfitAmount.add(taxProfitAmount);
                            totalProfitAmount = totalProfitAmount.add(profitAmount);
                            totalDeptSettleOverAmount = totalDeptSettleOverAmount.add(deptSettleOverAmount);
                            totalRebateAmount = totalRebateAmount.add(rebateAmount);
                            totalOverDateAmount = totalOverDateAmount.add(overDateAmount);
                        }
                        HyOrderDetail hyOrderDetail = hyOrderDetailService.getById(key);
                        HyOrderDetail save = addBackOrderDetails2(backOrder, hyOrderDetail, totalBackNum, reason, true);
                        save.setSettleAmount(totalSettleAmount);
                        save.setSaleNum(totalBackNum);
                        save.setSaleAmount(totalAmount);
                        save.setSettleAmountC(totalSettleAmountC);
                        save.setSettleAmountD(totalSettleAmountD);
                        save.setSettleAmountE(totalSettleAmountE);
                        save.setSettleSendAmount(totalSettleSendAmount);
                        save.setDeptSettleAmount(totalDeptSettleAmount);
                        save.setDeptProfitAmount(totalDeptProfitAmount);
                        save.setDeptProfitAmount(totalDeptProfitAmount);
                        save.setPayInvoiceTaxAmount(totalPayInvoiceTaxAmount);
                        save.setYtTaxAmount(totalYtTaxAmount);
                        save.setCheckAmount(totalCheckAmount);
                        save.setBjProfitAmount(totalBjProfitAmount);
                        save.setDrugProfitAmount(totalDrugProfitAmount);
                        save.setOverStandAmount(totalOverStandAmount);
                        save.setTaxRateDiff(totalTaxRateDiff);
                        save.setTaxProfitAmount(totalTaxProfitAmount);
                        save.setProfitAmount(totalProfitAmount);
                        save.setRebateAmount(totalRebateAmount);
                        save.setOverDateAmount(totalOverDateAmount);
                        hyOrderDetailService.saveOrUpdate(save);
                    });

                }
            }
        }
        backOrder.setTotalSaleAmount(totalSaleAmount);
        backOrder.setTotalBondAmount(totalCustomBond);
        backOrder.setReason(reason);
        //添加退货单
        save(backOrder);
        return true;
    }


    /**
     * 添加退货明细
     *
     * @param orderDetails
     * @param hyOrder      退货单
     * @param backNum
     * @param reason       退货原因
     * @param computeFee   是否进行费用计算
     * @return
     */
    private HyOrderDetail addBackOrderDetails2(HyOrder hyOrder, HyOrderDetail orderDetails, BigDecimal backNum, String reason, Boolean computeFee) {
        HyOrderDetail backOrderDetails = new HyOrderDetail();
        BeanUtil.copyProperties(orderDetails, backOrderDetails);
        backOrderDetails.setOrderDetailsId(IdWorker.getIdStr());
        backOrderDetails.setOrderId(hyOrder.getOrderId());
        backOrderDetails.setSaleNum(backNum);
        backOrderDetails.setSaleType(HySaleTypeEnum.CHC.getCode());
        backOrderDetails.setSendDate(hyOrder.getSendDate());
        backOrderDetails.setReason(reason);
        backOrderDetails.setParentId(orderDetails.getOrderDetailsId());
        backOrderDetails.setCreateTime(DateUtils.getNowDateTime());
        backOrderDetails.setUpdateTime(DateUtils.getNowDateTime());
        if (computeFee) {
            hyOrderUtils.computeFee(hyOrder, backOrderDetails, false, false);
        }
        return backOrderDetails;
    }


    /**
     * 构建退货单
     *
     * @param orderId
     * @return
     */
    private HyOrder initBackOrder(String orderId) {
        //查询原订单
        HyOrder order = getById(orderId);
        Integer sendType = order.getSendType();
        HyOrder backOrder = new HyOrder();
        BeanUtils.copyProperties(order, backOrder);
        backOrder.setProcessInstanceId(null);
        backOrder.setTakeDate(null);
        backOrder.setTakeDate(null);
        backOrder.setBankId(null);
        backOrder.setOutOrderNo("");
        backOrder.setCommentsXs(null);
        backOrder.setCommentsCw(null);
        backOrder.setCommentsSw(null);
        backOrder.setPrintTag(0);
        backOrder.setBankLists(null);
        backOrder.setSourceType(2);
        backOrder.setApplyIncId(null);
        backOrder.setCalculateState(0);
        backOrder.setSendState(0);
        backOrder.setRevokeState(0);
        //是否同步到海鹰系统
        backOrder.setSyncTag(0);
        backOrder.setCreateTime(DateUtils.getNowDateTime());
        backOrder.setUpdateTime(DateUtils.getNowDateTime());
        //调用单主
        backOrder.setParentId(orderId);
        Long companyId = order.getCompanyId();
        SysCompany company = companyService.getById(companyId);
        BaseUser user = baseUserService.getUserById(order.getUserId());
        //获取订单号
        String orderNo = businessUtils.getOrderNo(company, user);
        backOrder.setOrderId(orderNo);
        backOrder.setOrderNo(orderNo);
        //单据日期
        //backOrder.setCreateDate(DateUtils.getNowDate());
        backOrder.setOrderState(CommonConstants.INT_0);
        backOrder.setTakeAmount(new BigDecimal("0"));
        backOrder.setUserId(OpenHelper.getUserId());
        //退货日期
        backOrder.setSendDate(DateUtils.getNowDate());
        backOrder.setTotalSaleAmount(order.getTotalSaleAmount().multiply(new BigDecimal("-1")));
        if (sendType.equals(3)) {
            BigDecimal totalBondAmount = FlymeUtils.getBigDecimal(order.getTotalBondAmount(), "0");
            backOrder.setTotalBondAmount(totalBondAmount.multiply(new BigDecimal("-1")));
        }
        //退货通知单
        backOrder.setOrderType(HySaleTypeEnum.CHC.getCode());
        return backOrder;
    }


    @Override
    public Boolean updateSendState(String orderId, Map outOrderMap) {
        CriteriaUpdate cu = new CriteriaUpdate();
        String outOrderNo = MapUtil.getStr(outOrderMap, "单据编码");
        Date sendDate = MapUtil.getDate(outOrderMap, "单据日期");
        Integer backTag = MapUtil.getInt(outOrderMap, "backTag");
        //已提单
        cu.set(true, "sendState", CommonConstants.INT_1);
        if (FlymeUtils.isNotEmpty(outOrderNo)) {
            cu.set(true, "outOrderNo", outOrderNo);
        }
        if (backTag.equals(0)) {
            if (FlymeUtils.isNotEmpty(sendDate)) {
                cu.set(true, "sendDate", sendDate);
            }
        }
        if (backTag.equals(1)) {
            if (FlymeUtils.isNotEmpty(sendDate)) {
                cu.set(true, "sendDate", sendDate);
            }
        }
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }


    private List<BusHyorderReturn> getList(List<HyOrderDetail> orderDetailList) {
        List<BusHyorderReturn> list = new ArrayList<>();
        for (HyOrderDetail hyOrderDetail : orderDetailList) {
            BusHyorderReturn orderReturn = new BusHyorderReturn();
            BeanUtils.copyProperties(hyOrderDetail, orderReturn);
            orderReturn.setOrderDetailsReturnId(IdWorker.getId());
            orderReturn.setOverStandAmount(new BigDecimal("0"));
            orderReturn.setOverDateAmount(new BigDecimal("0"));
            list.add(orderReturn);
        }
        return list;
    }

    @Override
    public Boolean cancelRevokeProcess(String orderId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "revokeState", CommonConstants.INT_0);
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public Boolean cancelInvoiceInfo(String orderId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "invoiceState", CommonConstants.INT_0);
        cu.set(true, "invoiceRemark", "");
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public Boolean updateCaclulateOrder(String orderId, Integer status) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "calculateState", status);
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public Boolean updateCaclulateOrder(String orderId, String applyIncId, Integer status) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "calculateState", status);
        cu.set(true, "applyIncId", applyIncId);
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public ResultBody beforeGet(CriteriaQuery<HyOrder> cq, HyOrder hyOrder, EntityMap requestMap) {
        cq.select(HyOrder.class, "*");
        cq.joinSelect(BaseUser.class, "nickName");
        return super.beforeGet(cq, hyOrder, requestMap);
    }

    @Override
    public void afterGet(CriteriaQuery cq, EntityMap result) {
        String orderId = result.get("orderId");
        Long customId = result.get("customId");
        Long companyId = result.get("companyId");
        //发货方式
        Integer sendType = result.getInt("sendType");
        //客户名称回显
        if (FlymeUtils.isNotEmpty(customId)) {
            BusCustom custom = customService.getById(customId);
            if (FlymeUtils.isNotEmpty(custom)) {
                result.put("customId", custom.getCustomId());
                result.put("customName", custom.getCustomName());
            }
        }
        //业务员资保金回显
        Long saleManId = result.getLong("saleManId");
        if (FlymeUtils.isNotEmpty(saleManId)) {
            BusSaleman saleman = saleManService.getById(saleManId);
            AppPosition position = positionService.getById(saleman.getPositionId());
            result.put("positionNo", position.getPositionNo());
            //资信额度
            result.put("reputationAmount", FlymeUtils.getBigDecimal(saleman.getReputationAmount(), "0"));
        }
        //部门回显
        Long deptId = result.getLong("deptId");
        BusDept dept = deptService.getById(deptId);
        if (FlymeUtils.isNotEmpty(dept)) {
            result.put("deptName", dept.getDeptName());
            result.put("deptType", dept.getDeptType());
        }
        //收款方式
        Integer takeAmountType = result.getInt("takeAmountType", 0);
        String bankLists = "[]";
        if (takeAmountType.equals(1) || takeAmountType.equals(3)) {
            //实时收款或者认款记录
            List<BusPaymentOrder> paymentOrders = paymentOrderService.selectByOrderId(orderId);
            if (FlymeUtils.isNotEmpty(paymentOrders)) {
                List<HyBankItem> list = new ArrayList<>();
                for (BusPaymentOrder paymentOrder : paymentOrders) {
                    HyBankItem hyBankItem = new HyBankItem();
                    hyBankItem.setBankId(paymentOrder.getBankId());
                    hyBankItem.setPaymentId(paymentOrder.getPaymentId());
                    hyBankItem.setAmountType(paymentOrder.getAmountType());
                    hyBankItem.setPaymentOrderId(paymentOrder.getPaymentOrderId());
                    hyBankItem.setTakeAmount(paymentOrder.getTakeAmount());
                    hyBankItem.setTakeDate(paymentOrder.getTakeDate());
                    hyBankItem.setBankStatementId(paymentOrder.getBankStatementId());
                    hyBankItem.setIsEdit(true);
                    list.add(hyBankItem);
                }
                bankLists = JsonUtils.beanToJson(list);
            }
        }
        //余额
        if (takeAmountType.equals(2)) {
            List<HyBankItem> list = new ArrayList<>();
            //资保金余额
            BigDecimal surplusCustomBondAmount = saleManService.surplusCustomBondAmount(saleManId, companyId, orderId);
            HyBankItem hyBankItem = new HyBankItem();
            hyBankItem.setAmountType(2);
            hyBankItem.setIsEdit(true);
            hyBankItem.setTakeAmount(surplusCustomBondAmount);
            list.add(hyBankItem);
            bankLists = JsonUtils.beanToJson(list);
            result.put("amount", surplusCustomBondAmount);
        }
        result.put("bankLists", bankLists);
        //附件回显
        if (FlymeUtils.isNotEmpty(orderId)) {
            Long paymentId = cq.getLong("paymentId");
            List<EntityMap> fileList = fileService.selectFileListByFileType(orderId, "HyOrder", "");
            result.put("orderImage", fileList);
            if (FlymeUtils.isNotEmpty(paymentId)) {
                List<EntityMap> paymentImage = fileService.selectFileListByFileType(paymentId.toString(), "BusPayment", "");
                result.put("paymentImage", paymentImage);
            }
            List<EntityMap> drugList = hyOrderDetailService.selectOrderDetailsByOrderId(orderId, HySaleTypeEnum.CHA);
            result.put("drugList", drugList);
        }
        super.afterGet(cq, result);
    }

    @Override
    public ResultBody beforeDelete(CriteriaDelete<HyOrder> cd) {
        EntityMap map = cd.getRequestMap();
        //流程实例ID
        String processInstanceId = map.get("processInstanceId");
        //删除流程数据
        if (FlymeUtils.isNotEmpty(processInstanceId)) {
            ApiAssert.failure("请先撤销审批流程");
        }
        return super.beforeDelete(cd);
    }

    @Override
    public ResultBody afterDelete(CriteriaDelete cd, Serializable[] ids) {
        EntityMap map = cd.getRequestMap();
        Serializable orderId = map.get("ids");
        //删除订单明细
        hyOrderDetailService.delByOrderId(orderId);
        List<BusPayment> list = paymentService.selectByOrderIdAndAmountType(orderId, AmountTypeEnum.OrderAmount);
        if (FlymeUtils.isNotEmpty(list)) {
            for (BusPayment payment : list) {
                String bankStatementId = payment.getBankStatementId();
                bankStatementService.clearPaymentId(bankStatementId);
            }
        }
        paymentOrderService.removeByOrderId(orderId.toString());
        //删除实时现款和资保金认款单
        paymentService.deleteOrderPayment(orderId);
        return super.afterDelete(cd, ids);
    }

    /**
     * 设置订单信息(1)
     *
     * @param hyOrder
     */
    public void setHyOrderInfo(HyOrder hyOrder, BusSaleman saleMan) {
        hyOrder.setSaleManName(saleMan.getSaleManName());
        hyOrder.setBusinessCode(saleMan.getSaleManBusinessNo());
        //业务员职务
        hyOrder.setPositionId(saleMan.getPositionId());
        //发货方式 现款1 预收款2 资保金 3 全额资信 4
        Integer sendType = hyOrder.getSendType();
        //全额资信清空收款信息
        if (sendType.equals(SendTypeEnum.QZ.getCode())) {
            hyOrder.setTakeDate(null);
            hyOrder.setTakeAmount(new BigDecimal("0"));
            hyOrder.setBankId(null);
            hyOrder.setCustomBalanceId(null);
        }
        //预收款
        if (sendType.equals(SendTypeEnum.YSK.getCode())) {
            Long customBalanceId = hyOrder.getCustomBalanceId();
            BusCustomBalance busCustomBalance = customBalanceService.getById(customBalanceId);
            if (FlymeUtils.isNotEmpty(busCustomBalance)) {
                hyOrder.setBankId(busCustomBalance.getBankId());
                hyOrder.setTakeDate(busCustomBalance.getAmountDate());
            }
        }
    }


    /**
     * 订单明细添加时初始赋值
     */
    private void initBusOrderDetails(HyOrder order, HyOrderDetail orderDetail) {
        orderDetail.setOrderId(order.getOrderId());
        orderDetail.setCompanyId(order.getCompanyId());
        orderDetail.setOrganizationId(OpenHelper.getOrganizationId());
        orderDetail.setOrderDetailsState(CommonConstants.ENABLED);
        orderDetail.setSaleType(HySaleTypeEnum.CHA.getCode());
        orderDetail.setSendType(order.getSendType());
        orderDetail.setCustomBondTakeAmount(new BigDecimal("0"));
        orderDetail.setCustomReturnState(CommonConstants.INT_0);
        orderDetail.setCustomPolicy(CommonConstants.INT_0);
        orderDetail.setOutPrintTag(CommonConstants.INT_0);
    }


    /**
     * 获取订单打印信息
     *
     * @param orderId
     * @return
     */
    @Override
    public ResultBody getPrintInfo(String orderId) {
        EntityMap orderMap = getMapByOrderId(orderId);
        Long deptId = orderMap.getLong("deptId");
        String processInstanceId = orderMap.get("processInstanceId");
        String sendArea = orderMap.get("sendArea");
        Long saleManId = orderMap.getLong("saleManId");
        //收款金额
        BigDecimal takeAmount = orderMap.getBigDecimal("takeAmount");
        //收款日期
        Date takeDate = orderMap.get("takeDate");
        //票折金额
        BigDecimal totalDiscountAmount = orderMap.getBigDecimal("totalDiscountAmount");
        //销售金额
        BigDecimal totalSaleAmount = orderMap.getBigDecimal("totalSaleAmount").subtract(totalDiscountAmount);
        Long bankId = orderMap.getLong("bankId");
        Integer sendType = orderMap.get("sendType", 1);
        BusDept dept = deptService.getById(deptId);
        BaseUser user = userService.getById(orderMap.getLong("userId"));
        Long companyId = orderMap.getLong("companyId");
        SysCompany company = companyService.getById(companyId);
        BusSaleman saleman = saleManService.getById(saleManId);
        orderMap.put("companyName", company.getCompanyName());
        orderMap.put("deliveryTitle", "发货方式");
        orderMap.put("takeAmount", takeAmount);
        orderMap.put("takeDate", takeDate);
        orderMap.put("totalSaleAmount", totalSaleAmount);
        orderMap.put("sendType", sendType);
        orderMap.put("sendArea", sendArea);
        String orderTitle = "发货单";
        if (FlymeUtils.eqzero(totalSaleAmount)) {
            orderTitle = "样品发货单";
        }
        //制单人
        orderMap.put("nickName", user.getNickName());
        SysBank bank = bankService.getById(bankId);
        if (FlymeUtils.isNotEmpty(bank)) {
            //预收款银行名称
            orderMap.put("bankName", bank.getBankName());
        }
        orderMap.put("sendTypeName", SendTypeEnum.getName(sendType));
        Integer invoiceSendType = orderMap.getInt("invoiceSendType");
        orderMap.put("invoiceSendType", "货票同行");
        if (invoiceSendType.equals(2)) {
            orderMap.put("invoiceSendType", "单独邮寄");
        }
        //商品明细
        List<HyOrderDetail> orderDetails = hyOrderDetailService.selectByOrderId(orderId);
        //截取商品规格名称避免超长
        if (FlymeUtils.isNotEmpty(orderDetails)) {
            for (HyOrderDetail orderDetail : orderDetails) {
                String drugSpec = orderDetail.getDrugsSpec();
                if (drugSpec.length() > 50) {
                    orderDetail.setDrugsSpec(drugSpec.substring(0, 49));
                }
                //全额资信
                if (sendType.equals(4)) {
                    orderDetail.setReturnAmount(null);
                }
                String saleType = orderDetail.getSaleType();
                if (HySaleTypeEnum.Pz.getCode().equals(saleType)) {
                    orderDetail.setDrugsSpec("");
                    orderDetail.setDrugsName("票折");
                }
            }
            List<BusPaymentOrder> paymentOrders = paymentOrderService.selectByOrderId(orderId);
            if (FlymeUtils.isNotEmpty(paymentOrders)) {
                List<BusPaymentOrder> newBankList = new ArrayList<>();
                for (BusPaymentOrder paymentOrder : paymentOrders) {
                    Integer amountType = paymentOrder.getAmountType();
                    //实时收取
                    if (amountType.equals(1)) {
                        orderTitle = "认款发货单";
                        if (SendTypeEnum.ZBJ.getCode().equals(sendType)) {
                            String bankStatementId = paymentOrder.getBankStatementId();
                            BusBankStatement bankStatement = bankStatementService.getById(bankStatementId);
                            if (FlymeUtils.isNotEmpty(bankStatement)) {
                                orderMap.put("payUserName", bankStatement.getCustomName());
                            }
                        }
                    }
                    //排除余额抵扣记录
                    if (!amountType.equals(2)) {
                        newBankList.add(paymentOrder);
                    }
                }
                //收款记录数
                Integer bankSize = newBankList.size();
                //商品记录数
                Integer detailsSize = orderDetails.size();
                if (bankSize <= 1) {
                    HyOrderDetail orderDetail = orderDetails.get(0);
                    if (FlymeUtils.isNotEmpty(newBankList)) {
                        BusPaymentOrder paymentOrder = newBankList.get(0);
                        Long sysBankId = paymentOrder.getBankId();
                        Integer amountType = paymentOrder.getAmountType();
                        if (FlymeUtils.isNotEmpty(sysBankId)) {
                            SysBank sysBank = bankService.getById(sysBankId);
                            orderDetail.setReturnBank(sysBank.getBankName());
                            orderDetail.setReturnDate(paymentOrder.getTakeDate());
                            orderDetail.setReturnAmount(paymentOrder.getTakeAmount());
                        }
                    }
                    orderDetail.setRowspan(orderDetails.size());
                }

                if (bankSize > 1 && bankSize < detailsSize) {
                    int diff = detailsSize - bankSize;
                    for (int i = 0; i < bankSize; i++) {
                        HyOrderDetail orderDetail = orderDetails.get(i);
                        BusPaymentOrder paymentOrder = newBankList.get(i);
                        Long sysBankId = paymentOrder.getBankId();
                        SysBank sysBank = bankService.getById(sysBankId);
                        orderDetail.setReturnBank(sysBank.getBankName());
                        orderDetail.setReturnDate(paymentOrder.getTakeDate());
                        orderDetail.setReturnAmount(paymentOrder.getTakeAmount());
                        orderDetail.setRowspan(1);
                        if (i == bankSize - 1) {
                            orderDetail.setRowspan(diff + 1);
                        }
                    }
                }
                if (bankSize > 1 && bankSize == detailsSize) {
                    for (int i = 0; i < bankSize; i++) {
                        HyOrderDetail orderDetail = orderDetails.get(i);
                        BusPaymentOrder paymentOrder = newBankList.get(i);
                        Long sysBankId = paymentOrder.getBankId();
                        SysBank sysBank = bankService.getById(sysBankId);
                        orderDetail.setReturnBank(sysBank.getBankName());
                        orderDetail.setReturnDate(paymentOrder.getTakeDate());
                        orderDetail.setReturnAmount(paymentOrder.getTakeAmount());
                        orderDetail.setRowspan(1);
                    }
                }
                if (bankSize > 1 && bankSize > detailsSize) {
                    for (int i = 0; i < bankSize; i++) {
                        BusPaymentOrder paymentOrder = newBankList.get(i);
                        Long sysBankId = paymentOrder.getBankId();
                        SysBank sysBank = bankService.getById(sysBankId);
                        HyOrderDetail orderDetail = new HyOrderDetail();
                        if (i <= detailsSize - 1) {
                            orderDetail = orderDetails.get(i);
                        }
                        orderDetail.setReturnBank(sysBank.getBankName());
                        orderDetail.setReturnDate(paymentOrder.getTakeDate());
                        orderDetail.setReturnAmount(paymentOrder.getTakeAmount());
                        if (i > detailsSize - 1) {
                            orderDetails.add(orderDetail);
                        }
                        orderDetail.setRowspan(1);
                    }
                }
            } else {
                HyOrderDetail orderDetail = orderDetails.get(0);
                orderDetail.setRowspan(orderDetails.size());
            }

        }
        orderMap.put("orderTitle", orderTitle);
        orderMap.put("orderDetails", orderDetails);
        orderMap.put("createTime", DateUtils.getDateTime());
        BigDecimal useBalanceAmount = orderMap.getBigDecimal("useBalanceAmount");
        BigDecimal surplusBalanceAmount = orderMap.getBigDecimal("surplusBalanceAmount");
        if (FlymeUtils.gtzero(useBalanceAmount)) {
            orderMap.put("useBalanceAmount", "抵扣金额:" + useBalanceAmount);
        }
        if (FlymeUtils.gtzero(surplusBalanceAmount)) {
            orderMap.put("useBalanceAmount", "结余金额:" + surplusBalanceAmount);
        }
        if (FlymeUtils.isNotEmpty(processInstanceId)) {
            //查询审批人
            List<Comment> list = taskService.getProcessInstanceComments(processInstanceId, CommentTypeEnum.WC.toString());
            if (FlymeUtils.isNotEmpty(list)) {
                list = list.stream().filter(ConvertUtils.distinctByKey(Comment::getUserId)).collect(Collectors.toList());
                int i = 1;
                for (Comment comment : list) {
                    String userId = comment.getUserId();
                    BaseUser baseUser = userService.getUserById(Long.parseLong(userId));
                    List<String> roleCodes = roleService.selectRoleCodesByUserId(baseUser.getUserId());
                    String nickName = baseUser.getNickName();
                    //销售部长
                    if (roleCodes.contains("ROLE_XS_BZ")) {
                        orderMap.put("nickName_nqbz", nickName);
                    }
                    //商控员
                    if (roleCodes.contains("ROLE_SW_SKY")) {
                        orderMap.put("nickName_swsky", nickName);
                    }
                    //财务复核员
                    if (roleCodes.contains("ROLE_CW_FHY")) {
                        orderMap.put("nickName_cwfhy", nickName);
                    }
                    //财务部长
                    if (roleCodes.contains("ROLE_CW_CWBZ")) {
                        orderMap.put("nickName_cwbz", nickName);
                    }
                    //财务总监
                    if (roleCodes.contains("ROLE_CW_ZJ")) {
                        orderMap.put("nickName_cwzj", nickName);
                    }
                }
            }
        }
        return ResultBody.ok(orderMap);
    }


    /**
     * 获取订单打印信息
     *
     * @param orderId
     * @return
     */
    @Override
    public ResultBody getBackOrderPrintInfo(String orderId) {
        EntityMap orderMap = getMapByOrderId(orderId);
        Long deptId = orderMap.getLong("deptId");
        String parentId = orderMap.get("parentId");
        String processInstanceId = orderMap.get("processInstanceId");
        String sendArea = orderMap.get("sendArea");
        Long saleManId = orderMap.getLong("saleManId");
        //销售金额
        BigDecimal totalSaleAmount = orderMap.getBigDecimal("totalSaleAmount");
        Long bankId = orderMap.getLong("bankId");
        Integer sendType = orderMap.get("sendType", 1);
        BusDept dept = deptService.getById(deptId);
        BaseUser user = userService.getById(orderMap.getLong("userId"));
        Long companyId = orderMap.getLong("companyId");
        SysCompany company = companyService.getById(companyId);
        BusSaleman saleman = saleManService.getById(saleManId);
        orderMap.put("companyName", company.getCompanyName());
        orderMap.put("totalSaleAmount", totalSaleAmount);
        orderMap.put("sendType", sendType);
        orderMap.put("sendArea", sendArea);
        orderMap.put("createTime", DateUtils.getDateTime());
        //制单人
        orderMap.put("nickName", user.getNickName());
        SysBank bank = bankService.getById(bankId);
        if (FlymeUtils.isNotEmpty(bank)) {
            //预收款银行名称
            orderMap.put("bankName", bank.getBankName());
        }
        orderMap.put("sendTypeName", SendTypeEnum.getName(sendType));
        //父订单
        HyOrder parent = getById(parentId);
        if (FlymeUtils.isNotEmpty(parent)) {
            orderMap.put("parentOrderNo", parent.getOutOrderNo());
            orderMap.put("sendDate", parent.getSendDate());
        }
        //商品明细
        List<HyOrderDetail> orderDetails = hyOrderDetailService.selectByOrderId(orderId);
        //截取商品规格名称避免超长
        if (FlymeUtils.isNotEmpty(orderDetails)) {
            for (HyOrderDetail orderDetail : orderDetails) {
                String drugSpec = orderDetail.getDrugsSpec();
                if (drugSpec.length() > 50) {
                    orderDetail.setDrugsSpec(drugSpec.substring(0, 49));
                }
            }
            List<BusPaymentOrder> paymentOrders = paymentOrderService.selectByOrderId(orderId);
            if (FlymeUtils.isNotEmpty(paymentOrders)) {
                List<BusPaymentOrder> newBankList = new ArrayList<>();
                for (BusPaymentOrder paymentOrder : paymentOrders) {
                    Integer amountType = paymentOrder.getAmountType();
                    //排除余额抵扣记录
                    if (!amountType.equals(2)) {
                        newBankList.add(paymentOrder);
                    }
                }
                //收款记录数
                Integer bankSize = newBankList.size();
                //商品记录数
                Integer detailsSize = orderDetails.size();
                if (bankSize <= 1) {
                    HyOrderDetail orderDetail = orderDetails.get(0);
                    if (FlymeUtils.isNotEmpty(newBankList)) {
                        BusPaymentOrder paymentOrder = newBankList.get(0);
                        Long sysBankId = paymentOrder.getBankId();
                        Integer amountType = paymentOrder.getAmountType();
                        if (FlymeUtils.isNotEmpty(sysBankId)) {
                            //SysBank sysBank = bankService.getById(sysBankId);
                            orderDetail.setReturnBank(paymentOrder.getBankName());
                            orderDetail.setReturnDate(paymentOrder.getTakeDate());
                            orderDetail.setReturnAmount(paymentOrder.getTakeAmount());
                        }
                    }
                    orderDetail.setRowspan(orderDetails.size());
                }

                if (bankSize > 1 && bankSize < detailsSize) {
                    int diff = detailsSize - bankSize;
                    for (int i = 0; i < bankSize; i++) {
                        HyOrderDetail orderDetail = orderDetails.get(i);
                        BusPaymentOrder paymentOrder = newBankList.get(i);
                        Long sysBankId = paymentOrder.getBankId();
                        //SysBank sysBank = bankService.getById(sysBankId);
                        orderDetail.setReturnBank(paymentOrder.getBankName());
                        orderDetail.setReturnDate(paymentOrder.getTakeDate());
                        orderDetail.setReturnAmount(paymentOrder.getTakeAmount());
                        orderDetail.setRowspan(1);
                        if (i == bankSize - 1) {
                            orderDetail.setRowspan(diff + 1);
                        }
                    }
                }
                if (bankSize > 1 && bankSize == detailsSize) {
                    for (int i = 0; i < bankSize; i++) {
                        HyOrderDetail orderDetail = orderDetails.get(i);
                        BusPaymentOrder paymentOrder = newBankList.get(i);
                        Long sysBankId = paymentOrder.getBankId();
                        // SysBank sysBank = bankService.getById(sysBankId);
                        orderDetail.setReturnBank(paymentOrder.getBankName());
                        orderDetail.setReturnDate(paymentOrder.getTakeDate());
                        orderDetail.setReturnAmount(paymentOrder.getTakeAmount());
                        orderDetail.setRowspan(1);
                    }
                }
                if (bankSize > 1 && bankSize > detailsSize) {
                    for (int i = 0; i < bankSize; i++) {
                        BusPaymentOrder paymentOrder = newBankList.get(i);
                        Long sysBankId = paymentOrder.getBankId();
                        //SysBank sysBank = bankService.getById(sysBankId);
                        HyOrderDetail orderDetail = new HyOrderDetail();
                        if (i <= detailsSize - 1) {
                            orderDetail = orderDetails.get(i);
                        }
                        orderDetail.setReturnBank(paymentOrder.getBankName());
                        orderDetail.setReturnDate(paymentOrder.getTakeDate());
                        orderDetail.setReturnAmount(paymentOrder.getTakeAmount());
                        if (i > detailsSize - 1) {
                            orderDetails.add(orderDetail);
                        }
                        orderDetail.setRowspan(1);
                    }
                }
            } else {
                HyOrderDetail orderDetail = orderDetails.get(0);
                orderDetail.setRowspan(orderDetails.size());
            }
        }

        orderMap.put("orderDetails", orderDetails);
        orderMap.put("chineseAmount", NumberChineseFormatter.format(totalSaleAmount.doubleValue(), true, true));
        if (FlymeUtils.isNotEmpty(processInstanceId)) {
            //查询审批人
            List<Comment> list = taskService.getProcessInstanceComments(processInstanceId, CommentTypeEnum.WC.toString());
            if (FlymeUtils.isNotEmpty(list)) {
                list = list.stream().filter(ConvertUtils.distinctByKey(Comment::getUserId)).collect(Collectors.toList());
                int i = 1;
                for (Comment comment : list) {
                    String userId = comment.getUserId();
                    BaseUser baseUser = userService.getUserById(Long.parseLong(userId));
                    List<String> roleCodes = roleService.selectRoleCodesByUserId(baseUser.getUserId());
                    String nickName = baseUser.getApplyName();
                    //销售部长
                    if (roleCodes.contains("ROLE_XS_BZ")) {
                        orderMap.put("nickName_nqbz", nickName);
                    }
                    //质量部
                    if (roleCodes.contains("ROLE_ZL_FHY")) {
                        orderMap.put("nickName_zlfhy", nickName);
                    }
                }
            }
        }
        return ResultBody.ok(orderMap);
    }


    @Override
    public Boolean updatePrintTag(String orderId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.setSql(true, "printTag=printTag+1");
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public Boolean updateOutPrintTag(String orderId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.setSql(true, "outPrintTag=outPrintTag+1");
        cu.in(true, "orderId", orderId.split(","));
        return update(cu);
    }

    @Override
    public Boolean updateOutPrintTag2(String orderId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.setSql(true, "outPrintTag2=outPrintTag2+1");
        cu.in(true, "orderId", orderId.split(","));
        return update(cu);
    }

    @Override
    public Boolean setOutPrintTag(String orderId, Integer outPrintTag) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "outPrintTag", outPrintTag);
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public Boolean setOutPrintTag2(String orderId, Integer outPrintTag2) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "outPrintTag2", outPrintTag2);
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }


    @Override
    public Boolean updateOrderInvoiceInfo(String orderId, Integer invoiceSendType, String invoiceRemark) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "invoiceSendType", invoiceSendType);
        cu.set(true, "invoiceRemark", invoiceRemark);
        cu.set(true, "invoiceState", CommonConstants.INT_1);
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public Boolean updateInvoiceState(String orderId, Integer invoiceState) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "invoiceState", invoiceState);
        cu.eq(true, "orderId", orderId);
        return update(cu);
    }

    @Override
    public List<HyOrder> selectBySendState(Integer sendState) {
        CriteriaQuery cq = new CriteriaQuery(HyOrder.class);
        cq.eq("sendState", sendState);
        return list(cq);
    }


    private List<HyOrder> selectByApplyedOrder() {
        CriteriaQuery cq = new CriteriaQuery(HyOrder.class);
        //未同步
        cq.eq("syncTag", 0);
        //已审批完成
        cq.eq("orderState", 2);
        cq.eq("orderType", HySaleTypeEnum.CHA.getCode());
        //财务意见
        cq.isNotNull("commentsCw");
        cq.isNotNull("commentsSw");
        cq.isNotNull("commentsXs");
        //一次取一条
        cq.limit(1);
        return list(cq);
    }

    private List<HyOrder> selectByApplyedBackOrder() {
        CriteriaQuery cq = new CriteriaQuery(HyOrder.class);
        //未同步
        cq.eq("syncTag", 0);
        //已审批完成
        cq.eq("orderState", 2);
        cq.eq("orderType", HySaleTypeEnum.CHC.getCode());
        cq.isNotNull("commentsXs");
        cq.isNotNull("commentsCw");
        //一次取一条
        cq.limit(1);
        return list(cq);
    }

    private HyOrder selectLastOrder(String hostName) {
        CriteriaQuery<HyOrder> cq = new CriteriaQuery(HyOrder.class);
        cq.eq("orderState", CommonConstants.INT_0);
        cq.eq("hostName", hostName);
        cq.orderByDesc("createTime", "orderId");
        cq.limit(1);
        return getOne(cq);
    }

    /**
     * 同步海鹰订单
     *
     * @param dbName
     * @param orderNo
     * @return
     */
    @Override
    public ResultBody syncOrder(String dbName, String orderNo) {
        if (FlymeUtils.isNotEmpty(orderNo)) {
            String [] ordeNos=orderNo.split(",");
            Long companyId = OpenHelper.getCompanyId();
            for (String o : ordeNos) {
                HyOrder hyOrder = getOutOrderNo(o,companyId);
                if (FlymeUtils.isEmpty(hyOrder)) {
                    hyOrder = new HyOrder();
                    hyOrder.setOrderId(IdWorker.getIdStr());
                    hyOrder.setRevokeState(0);
                    hyOrder.setPrintTag(0);
                    hyOrder.setOutPrintTag(0);
                    hyOrder.setOutPrintTag2(0);
                    hyOrder.setSendState(0);
                    hyOrder.setOrderState(-1);
                    hyOrder.setSyncTag(1);
                    hyOrder.setSourceType(1);
                    //核算状态
                    hyOrder.setCalculateState(0);
                }
                EntityMap order = hyRemoteOrderService.getOutOrderAllFieldById(dbName, o);
                if (FlymeUtils.isNotEmpty(order)) {
                    String orderId = MapUtil.getStr(order, "单据编码");
                    //Map outOrderMap = hyRemoteOrderService.getOutOrderNo(dbName, orderId);
                    String parentId = order.get("调用单主");
                    String orderDate = MapUtil.getStr(order, "单据日期");
                    String outType = MapUtil.getStr(order, "出库方式");
                    String customAddress = MapUtil.getStr(order, "收货地址");
                    String customUserName = MapUtil.getStr(order, "收货人姓名");
                    String cwApply = MapUtil.getStr(order, "财务审核");
                    String xsApply = MapUtil.getStr(order, "业务审核");
                    String swNameApply = MapUtil.getStr(order, "审核人");
                    Date swDateApply = MapUtil.getDate(order, "审核时间");
                    String swApply = MapUtil.getStr(order, "审核意见");
                    String customUserTel = MapUtil.getStr(order, "收货人电话");
                    BigDecimal totalAmount = order.getBigDecimal("合计金额");
                    //String outOrderNo = MapUtil.getStr(outOrderMap, "单据编号");
                    hyOrder.setOutOrderNo(orderId);
                    hyOrder.setOrderNo(parentId);
                    //hyOrder.setParentId(parentId);
                    hyOrder.setCommentsXs(xsApply);
                    hyOrder.setCommentsCw(cwApply);
                    hyOrder.setCommentsSw(swNameApply + "#" + swDateApply + "#" + swApply);
                    hyOrder.setCompanyId(companyId);
                    hyOrder.setOrganizationId(OpenHelper.getOrganizationId());
                    if(outType.equals("CKA")){
                        outType="CHA";
                    }
                    hyOrder.setOrderType(outType);
                    hyOrder.setCustomUserTel(customUserTel);
                    hyOrder.setCustomAddress(customAddress);
                    hyOrder.setCustomUserName(customUserName);
                    hyOrder.setTotalSaleAmount(totalAmount);
                    if (FlymeUtils.isNotEmpty(orderDate)) {
                        orderDate = orderDate.substring(0, 10);
                        hyOrder.setCreateDate(DateUtils.parseDate(orderDate));
                        hyOrder.setSendDate(DateUtils.parseDate(orderDate));
                    }
                    Date sendDate = MapUtil.getDate(order, "单据日期");
                    //if (FlymeUtils.isNotEmpty(sendDate)) {
                       // hyOrder.setSendDate(sendDate);
                   // }

                    String deptNo = MapUtil.getStr(order, "部门编码");
                    hyOrder.setHyDeptNo(deptNo);
                    //关联数据查询
                    BusDeptHy busDeptHy = deptHyService.getByHyDeptId(deptNo, companyId);
                    Long deptId = null;
                    BusDept dept = null;
                    if (FlymeUtils.isNotEmpty(busDeptHy)) {
                        deptId = busDeptHy.getDeptId();
                        hyOrder.setDeptId(deptId);
                        dept = deptService.getById(deptId);
                    }
                    String businessCode = MapUtil.getStr(order, "业务员");
                    hyOrder.setBusinessCode(businessCode);
                    hyOrder.setSaleManName(businessCode);
                    String customCode = MapUtil.getStr(order, "单位编码");
                    hyOrder.setCustomCode(customCode);
                    //查询购货方
                    BusCustom custom = customService.selectByCustomCode(customCode, companyId);
                    Long customId = null;
                    if (FlymeUtils.isNotEmpty(custom)) {
                        customId = custom.getCustomId();
                        hyOrder.setCustomId(customId);
                        hyOrder.setSendArea(custom.getAreaName());
                        hyOrder.setSendAreaId(custom.getAreaCode());
                        hyOrder.setCustomCode(customCode);
                    }
                    String userName = MapUtil.getStr(order, "开票员");
                    hyOrder.setNickName(userName);
                    BaseUser baseUser = userService.selectByNickNameAndTenantId(userName, "flp");
                    if (FlymeUtils.isNotEmpty(baseUser)) {
                        hyOrder.setUserId(baseUser.getUserId());
                        hyOrder.setHostName(baseUser.getHostName());
                    }
                    //查询业务员
                    BusSaleman saleman = saleManService.getBySaleManBusinessNo(deptId, businessCode);
                    Long saleManId = null;
                    if (FlymeUtils.isNotEmpty(saleman)) {
                        saleManId = saleman.getSaleManId();
                        hyOrder.setSaleManId(saleman.getSaleManId());
                        hyOrder.setSaleManName(saleman.getSaleManName());
                        String areaShortName = saleManService.getAreaShortName(saleman);
                        hyOrder.setBusinessArea(areaShortName);
                        hyOrder.setPositionId(saleman.getPositionId());
                        Long areaId = hyOrderUtils.getAreaId(saleman);
                        hyOrderUtils.setSaleManInfo(hyOrder, saleman);
                    }

                    //保存入订单主
                    saveOrUpdate(hyOrder);
                    List<EntityMap> detailsList = hyRemoteOrderService.queryOutHyOrderDetailList(dbName, o);
                    if (FlymeUtils.isNotEmpty(detailsList)) {
                        for (EntityMap entityMap : detailsList) {
                            String orderDetailsId = MapUtil.getStr(entityMap, "orderDetailsId")+companyId;
                            String orderCode = MapUtil.getStr(entityMap, "orderCode");
                            String drugsName = MapUtil.getStr(entityMap, "drugsName");
                            String drugsSpec = MapUtil.getStr(entityMap, "drugsSpec");
                            String invoiceNo = MapUtil.getStr(entityMap, "invoiceNo");
                            String drugNo = MapUtil.getStr(entityMap, "drugNo");
                            String storeCode = MapUtil.getStr(entityMap, "storeCode");
                            String storeName = MapUtil.getStr(entityMap, "storeName");
                            String drugType = MapUtil.getStr(entityMap, "drugType");
                            Integer drugLotId = MapUtil.getInt(entityMap, "drugLotId");
                            Date generationDate = MapUtil.getDate(entityMap, "generationDate");
                            Date expirationDate = MapUtil.getDate(entityMap, "expirationDate");
                            Integer drugJr = MapUtil.getInt(entityMap, "drugJr");
                            BigDecimal drugJs = entityMap.getBigDecimal("drugJs");

                            String drugLotNo = MapUtil.getStr(entityMap, "drugLotNo");
                            String producersName = MapUtil.getStr(entityMap, "producersName");
                            BigDecimal saleNum = entityMap.getBigDecimal("saleNum");
                            BigDecimal salePrice = entityMap.getBigDecimal("salePrice");
                            BigDecimal saleAmount = entityMap.getBigDecimal("saleAmount");
                            BigDecimal costPrice = entityMap.getBigDecimal("costPrice");
                            BigDecimal costAmount = entityMap.getBigDecimal("costAmount");

                            HyOrderDetail orderDetail = hyOrderDetailService.getById(orderDetailsId);
                            if (FlymeUtils.isEmpty(orderDetail)) {
                                orderDetail = new HyOrderDetail();
                                orderDetail.setOrderId(hyOrder.getOrderId());
                                orderDetail.setOrderDetailsId(orderDetailsId);
                                orderDetail.setCompanyId(OpenHelper.getCompanyId());
                                orderDetail.setDeptId(deptId);
                                orderDetail.setCustomId(customId);
                                orderDetail.setCustomCode(customCode);
                                orderDetail.setSaleManId(saleManId);
                                orderDetail.setOrganizationId(hyOrder.getOrganizationId());
                                BusDrugs drugs = drugsService.selectByDrugNo(drugNo, companyId);
                                if (FlymeUtils.isNotEmpty(drugs)) {
                                    orderDetail.setDrugType(drugs.getDrugType());
                                }
                            }
                            orderDetail.setProducersName(producersName);
                            orderDetail.setDrugNo(drugNo);

                            orderDetail.setInvoiceNo(invoiceNo);
                            orderDetail.setGenerationDate(generationDate);
                            orderDetail.setExpirationDate(expirationDate);
                            orderDetail.setCostPrice(costPrice);
                            orderDetail.setCostAmount(costAmount);
                            orderDetail.setSalePrice(salePrice);
                            orderDetail.setDrugLotId(drugLotId);
                            orderDetail.setSaleAmount(saleAmount);
                            orderDetail.setDrugsName(drugsName);
                            orderDetail.setDrugsSpec(drugsSpec);
                            orderDetail.setDrugLotNo(drugLotNo);
                            orderDetail.setOrderCode(orderCode);
                            orderDetail.setCalculateState(0);
                            orderDetail.setSaleType(HySaleTypeEnum.CHA.getCode());
                            orderDetail.setSaleNum(saleNum);
                            orderDetail.setDrugJr(drugJr);
                            orderDetail.setDrugType(drugType);
                            orderDetail.setStoreName(storeName);
                            orderDetail.setDrugJs(drugJs);
                            orderDetail.setPrintDrugJs(drugJs);
                            orderDetail.setHostName(hyOrder.getHostName());
                            orderDetail.setStoreCode(storeCode);
                            orderDetail.setSendDate(sendDate);
                            if (FlymeUtils.isNotEmpty(sendDate)) {
                                String[] formatDate = DateUtils.formatDate(sendDate, null).split("-");
                                orderDetail.setSendYear(Integer.valueOf(formatDate[0]));
                                orderDetail.setSendMonth(Integer.valueOf(formatDate[1]));
                                orderDetail.setSendDay(Integer.valueOf(formatDate[2]));
                            }
                            orderDetail.setOrderDetailsState(CommonConstants.ENABLED);
                            //计算结算费用
                            //hyOrderUtils.computeFee(hyOrder, orderDetail, false, false);
                            hyOrderDetailService.saveOrUpdate(orderDetail);
                        }
                    }
                    EntityMap params = new EntityMap();
                    params.put("orderId", orderId);
                    params.put("syncState", 1);
                    hyRemoteOrderService.updateSyncState(dbName, params);
                }
            }
        }
        return ResultBody.ok();
    }


    /**###########################################备份方法###########################################################*/

    /**
     * 生成订单ID
     */
    private EntityMap getOrderConfigBack(Long companyId, BaseUser baseUser) {
        EntityMap result = new EntityMap();
        String hostName = baseUser.getHostName();
        ApiAssert.isNotEmpty("主机名未配置", hostName);
        String dbName = businessUtils.getDbName(companyId);
        EntityMap sysProperties = hyRemoteOrderService.selectSysProperties(dbName, hostName);
        ApiAssert.isNotEmpty("站点配置不存在", sysProperties);
        //站点编号
        String sysid = sysProperties.get("sysid");
        HyOrder hyOrder = selectLastOrder(hostName);
        //上一次的出订单主编号
        String lastOrderNo = "";
        //上一次的出订单细编号
        String lastOrderDetailsId = "";
        if (FlymeUtils.isNotEmpty(hyOrder)) {
            lastOrderNo = hyOrder.getOrderId();
            lastOrderDetailsId = hyOrderDetailService.selectLastOrderDetailsId(hyOrder.getCompanyId(), hyOrder.getHostName());
        } else {
            lastOrderNo = sysProperties.get("orderNo");
            lastOrderDetailsId = sysProperties.get("orderDetailsId");
        }
        if (FlymeUtils.isEmpty(lastOrderNo)) {
            //初始值
            lastOrderNo = "0";
        } else {
            lastOrderNo = Integer.parseInt(lastOrderNo.substring(4)) + "";
        }
        if (FlymeUtils.isEmpty(lastOrderDetailsId)) {
            //初始值
            lastOrderDetailsId = "0";
        } else {
            lastOrderDetailsId = Integer.parseInt(lastOrderDetailsId.substring(4)) + "";
        }
        String newOrderNo = sysid + String.format("%010d", Integer.parseInt(lastOrderNo) + 1);
        String newOrderDetailsId = sysid + String.format("%012d", Integer.parseInt(lastOrderDetailsId) + 1);
        result.put("orderId", newOrderNo);
        result.put("orderDetailsId", newOrderDetailsId);
        result.put("sysid", sysid);
        return result;
    }


    private void init() {
        CriteriaQuery cq = new CriteriaQuery(HyOrder.class);
        cq.in("companyId", 5L, 1018L);
        List<HyOrder> list = list(cq);
        for (HyOrder order : list) {
            Integer sendType = order.getSendType();

            String bankList = order.getBankLists();
            if (FlymeUtils.isNotEmpty(bankList)) {
                List<HyBankItem> bankItems = JsonUtils.toList(bankList, HyBankItem.class);
                for (HyBankItem bankItem : bankItems) {
                    Long paymentId = bankItem.getPaymentId();
                    if (FlymeUtils.isNotEmpty(paymentId)) {
                        BusPaymentOrder paymentOrder = paymentOrderService.findByPaymentIdAndOrderId(order.getOrderId(), bankItem.getPaymentId());
                        if (FlymeUtils.isNotEmpty(paymentOrder)) {
                            paymentOrder.setAmountType(bankItem.getAmountType());
                            paymentOrder.setTakeAmount(bankItem.getTakeAmount());
                            paymentOrder.setSendType(order.getSendType());
                            paymentOrder.setBankStatementId(bankItem.getBankStatementId());
                            // paymentOrderService.updateById(paymentOrder);
                        } else {
                            paymentOrder = new BusPaymentOrder();
                            paymentOrder.setPaymentId(bankItem.getPaymentId());
                            paymentOrder.setAmountType(bankItem.getAmountType());
                            paymentOrder.setSendType(sendType);
                            paymentOrder.setCompanyId(order.getCompanyId());
                            paymentOrder.setBankStatementId(bankItem.getBankStatementId());
                            paymentOrder.setTakeAmount(bankItem.getTakeAmount());
                            paymentOrder.setUseAmount(order.getTotalSaleAmount());
                            paymentOrder.setOrderId(order.getOrderId());
                            paymentOrder.setCustomId(order.getCustomId().toString());
                            paymentOrder.setTakeDate(bankItem.getTakeDate());
                            paymentOrder.setBankId(bankItem.getBankId());
                            // paymentOrderService.save(paymentOrder);
                            System.out.println("33333333333333333333333333::::::" + order.getOrderId());
                        }
                    }
                }
            }

                 /*   List<HyBankItem> list2 = new ArrayList<>();
                    HyBankItem hyBankItem = new HyBankItem();
                    hyBankItem.setBankId(order.getBankId());
                    hyBankItem.setAmountType(1);
                    hyBankItem.setTakeAmount(order.getTakeAmount());
                    hyBankItem.setTakeDate(order.getTakeDate());

                    BusPayment payment = paymentService.getByProperty("orderDetailsId", order.getOrderId());
                    if (FlymeUtils.isNotEmpty(payment)) {
                        hyBankItem.setPaymentId(payment.getPaymentId());
                        list2.add(hyBankItem);
                        String bankLists = JsonUtils.beanToJson(list2);
                        order.setBankLists(bankLists);
                        updateById(order);
                    } else {
                        SysBank bank = bankService.getById(order.getBankId());
                        BusPayment payment1 = new BusPayment();
                        payment1.setOrderId(order.getOrderId());
                        payment1.setOrderDetailsId(order.getOrderId());
                        payment1.setTitle("现款收款单");
                        payment1.setCompanyId(order.getCompanyId());
                        payment1.setAmountType("OrderAmount");
                        payment1.setAmount(order.getTakeAmount());
                        payment1.setAmountDate(order.getTakeDate());
                        payment1.setBankId(order.getBankId());
                        payment1.setBankNo(bank.getBankNo());
                        payment1.setBankName(bank.getBankName());
                        payment1.setPaymentState(2);
                        payment1.setUserId(order.getUserId());
                        payment1.setCustomId(order.getCustomId().toString());
                        payment1.setPrintTag(0);
                        payment1.setAdvanceState(0);
                        payment1.setCreateTime(order.getCreateTime());
                        paymentService.save(payment1);
                    }*/


        }

    }

    /**
     * 保存认款记录
     *
     * @param paymentList
     * @param order
     */
    private void saveBusPaymentOrder() {
        List<BusPayment> paymentList = paymentService.selectByOrderIdAndAmountType(null, AmountTypeEnum.OrderAmount, CommonConstants.INT_2);
        if (FlymeUtils.isNotEmpty(paymentList)) {
            for (BusPayment payment : paymentList) {
                CriteriaQuery cq = new CriteriaQuery(BusPaymentOrder.class);
                cq.eq("paymentId", payment.getPaymentId());
                List<BusPaymentOrder> list = paymentOrderService.list(cq);
                if (FlymeUtils.isNotEmpty(list)) {
                    for (BusPaymentOrder busPaymentOrder : list) {
                        BigDecimal amount = busPaymentOrder.getUseAmount();
                        BigDecimal s = payment.getSurplusAmount().subtract(amount);
                        //更新剩余金额
                        payment.setSurplusAmount(s);
                        paymentService.updateById(payment);
                    }
                }
            }
        }
    }

    private void init2() {
        CriteriaQuery cq = new CriteriaQuery(HyOrder.class);
        cq.in("companyId", 5L, 1018L, 1017L);
        List<HyOrder> list = list(cq);
        for (HyOrder order : list) {
            Integer sendType = order.getSendType();
            if (FlymeUtils.isNotEmpty(sendType) && sendType.equals(3)) {
                List<HyOrderDetail> details = hyOrderDetailService.selectByOrderId(order.getOrderId());
                BigDecimal customBonTotal = new BigDecimal("0");
                for (HyOrderDetail detail : details) {
                    BigDecimal customBond = FlymeUtils.getBigDecimal(detail.getCustomBond(), "0");
                    customBonTotal = customBonTotal.add(customBond);
                }
                order.setTotalBondAmount(customBonTotal);
                updateById(order);
            }
        }
    }


    /**
     * 获取订单打印信息
     *
     * @param orderId
     * @return
     */
    @Override
    public ResultBody getOutOrderPrint(String orderId) {
        EntityMap result = new EntityMap();
        String template = sysPrintDesignerService.getContentByDesignCode("PrintDesigner01");
        result.put("template", template);
        List<HyOrder> list = getOrderList(orderId);
        List<EntityMap> datas = new ArrayList<>();
        for (HyOrder order : list) {
            EntityMap map = new EntityMap();
            Long companyId = order.getCompanyId();
            Long customId = order.getCustomId();
            BusCustom custom = customService.getById(customId);
            map.put("orderId", order.getOrderId());
            map.put("outOrderNo", order.getOutOrderNo());
            map.put("barcode", "CKA" + order.getOutOrderNo());
            map.put("remark", "厂检,出库单");
            //客户名称
            map.put("customName", custom.getCustomName());
            Long userId = OpenHelper.getUserId();
            BaseUser baseUser = userService.getById(userId);
            SysCompany company = companyService.getById(companyId);
            //发货地址
            map.put("companyAddress", company.getCompanyAddress());
            //发货方
            map.put("companyName", company.getCompanyShortName());
            BigDecimal drugJs = hyOrderDetailService.countDrugJs(order.getOrderId());
            List<String> drugsName = hyOrderDetailService.getDrugsNames(order.getOrderId());
            if (FlymeUtils.isNotEmpty(drugsName)) {
                if (drugsName.size() == 1) {
                    //商品名称
                    map.put("drugsName", drugsName.get(0));
                } else {
                    map.put("drugsName", drugsName.get(0) + "...");
                }
            }
            //件数
            map.put("drugJs", drugJs);
            //整件数
            map.put("drugJsCount", drugJs.setScale(0, BigDecimal.ROUND_UP));
            map.put("totalDrugJs", drugJs.setScale(0, BigDecimal.ROUND_UP));
            //出库日期
            map.put("outDate", DateUtils.getNowDate());
            //打印日期
            map.put("printDate", DateUtils.getNowDate());
            //发货人
            map.put("outNickName", OpenHelper.getNickName());
            //发货人电话
            map.put("mobile", baseUser.getMobile());

            //收货人电话
            map.put("customUserTel", order.getCustomUserTel());
            //收货人地址
            map.put("customAddress", order.getCustomAddress());
            //收货人
            map.put("customUserName", order.getCustomUserName());
            datas.add(map);
        }
        result.put("dataList", datas);
        return ResultBody.ok(result);
    }

    /**
     * 获取出库单合并打印信息
     *
     * @param orderId
     * @return
     */
    @Override
    public ResultBody getMergeOutOrderPrint(String orderId) {
        EntityMap result = new EntityMap();
        String template = sysPrintDesignerService.getContentByDesignCode("PrintDesigner01");
        result.put("template", template);
        EntityMap checkMap = checkMergeOrderList(orderId);
        Integer addressCount = checkMap.getInt("customAddressCount");
        Integer userCount = checkMap.getInt("userCount");
        if (addressCount > 1) {
            ApiAssert.failure("存在多个收货地址");
        }
        if (userCount > 1) {
            ApiAssert.failure("存在多个收货人");
        }
        List<HyOrder> list = getOrderList(orderId);
        List<EntityMap> datas = new ArrayList<>();
        EntityMap map = new EntityMap();

        BigDecimal drugJs = hyOrderDetailService.countDrugJs(orderId);
        HyOrder order = list.get(0);
        Long companyId = order.getCompanyId();
        Long customId = order.getCustomId();
        BusCustom custom = customService.getById(customId);
        map.put("orderId", order.getOrderId());
        map.put("barcode", "CKA" + order.getOutOrderNo());
        map.put("remark", "厂检,出库单");
        //客户名称
        map.put("customName", custom.getCustomName());
        Long userId = OpenHelper.getUserId();
        BaseUser baseUser = userService.getById(userId);
        SysCompany company = companyService.getById(companyId);
        //发货地址
        map.put("companyAddress", company.getCompanyAddress());
        //发货方
        map.put("companyName", company.getCompanyShortName());
        List<String> drugsName = hyOrderDetailService.getDrugsNames(orderId);
        if (FlymeUtils.isNotEmpty(drugsName)) {
            if (drugsName.size() == 1) {
                //商品名称
                map.put("drugsName", drugsName.get(0));
            } else {
                map.put("drugsName", drugsName.get(0) + "...");
            }
        }
        List<String> outOrderNos = new ArrayList<>();
        if (FlymeUtils.isNotEmpty(list)) {
            for (HyOrder hyOrder : list) {
                outOrderNos.add(hyOrder.getOutOrderNo());
            }
        }
        map.put("outOrderNo", ConvertUtils.listToString(outOrderNos));
        //件数
        map.put("drugJs", drugJs);
        //总件数
        map.put("drugJsCount", drugJs.setScale(0, BigDecimal.ROUND_UP));
        map.put("totalDrugJs", drugJs.setScale(0, BigDecimal.ROUND_UP));
        //出库日期
        map.put("outDate", DateUtils.getNowDate());
        //打印日期
        map.put("printDate", DateUtils.getNowDate());
        //发货人
        map.put("outNickName", OpenHelper.getNickName());
        //发货人电话
        map.put("mobile", baseUser.getMobile());

        //收货人电话
        map.put("customUserTel", order.getCustomUserTel());
        //收货人地址
        map.put("customAddress", order.getCustomAddress());
        //收货人
        map.put("customUserName", order.getCustomUserName());
        datas.add(map);
        result.put("dataList", datas);
        return ResultBody.ok(result);
    }


    /**
     * 查询订单
     *
     * @param orderId
     * @return
     */
    public List<HyOrder> getOrderList(String orderId) {
        CriteriaQuery cq = new CriteriaQuery<>(HyOrder.class);
        cq.in(true, "orderId", orderId.split(","));
        return list(cq);
    }

    /**
     * 获取合并打印订单信息
     *
     * @param orderId
     * @return
     */
    private EntityMap checkMergeOrderList(String orderId) {
        CriteriaQuery cq = new CriteriaQuery<>(HyOrder.class);
        cq.select("orderId", "count(DISTINCT customAddress) customAddressCount", "count(DISTINCT customUserName) userCount");
        cq.in(true, "orderId", orderId.split(","));
        cq.groupBy("customAddress");
        List<EntityMap> list = selectEntityMap(cq);
        if (FlymeUtils.isNotEmpty(list) && list.size() > 1) {
            ApiAssert.failure("存在多个地址,禁止合并打印");
        }
        return findOne(cq);
    }


    public HyOrder selectLastOrderByCustomId(Long saleManId, Long customId) {
        CriteriaQuery<HyOrder> cq = new CriteriaQuery(HyOrder.class);
        cq.eq("orderState", CommonConstants.INT_2);
        cq.eq("saleManId", saleManId);
        cq.eq("customId", customId);
        cq.orderByDesc("createTime");
        cq.limit(1);
        return getOne(cq);
    }

}
